0% found this document useful (0 votes)
10 views1,332 pages

Querys

Uploaded by

sergio Avalos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views1,332 pages

Querys

Uploaded by

sergio Avalos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1332

IBM i

7.4

Database
Performance and Query Optimization

IBM
Note
Before using this information and the product it supports, read the information in “Notices” on page
1313.

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, 2019.
US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract with
IBM Corp.
Contents

Performance and query optimization......................................................................1


What's new for IBM i 7.4..............................................................................................................................1
Print PDF.................................................................................................................................................... 12
Query engine overview.............................................................................................................................. 13
SQE and CQE engines...........................................................................................................................13
Query dispatcher.................................................................................................................................. 14
Statistics manager................................................................................................................................15
Global Statistics Cache........................................................................................................................ 16
Plan cache............................................................................................................................................ 16
Data access methods.................................................................................................................................19
Permanent objects & access methods................................................................................................ 19
Table................................................................................................................................................19
Table scan..................................................................................................................................20
Table probe................................................................................................................................21
Radix index......................................................................................................................................22
Radix index scan........................................................................................................................22
Radix index probe......................................................................................................................23
Encoded vector index..................................................................................................................... 25
Encoded vector index RRN probe............................................................................................. 26
EVI probe................................................................................................................................... 27
EVI index-only access............................................................................................................... 29
EVI symbol table scan...............................................................................................................29
EVI symbol table probe.............................................................................................................32
Temporary objects & access methods.................................................................................................34
Temporary hash table..................................................................................................................... 34
Hash table scan......................................................................................................................... 35
Hash table probe....................................................................................................................... 36
Temporary sorted list......................................................................................................................37
Sorted list scan.......................................................................................................................... 38
Sorted list probe........................................................................................................................ 39
Temporary distinct sorted list.........................................................................................................40
Sorted list scan.......................................................................................................................... 40
Temporary list................................................................................................................................. 41
List scan..................................................................................................................................... 41
Temporary values list......................................................................................................................42
Values list scan.......................................................................................................................... 43
Temporary row number list............................................................................................................ 43
Row number list scan................................................................................................................ 43
Row number list probe.............................................................................................................. 45
Temporary bitmap.......................................................................................................................... 46
Bitmap scan...............................................................................................................................47
Bitmap probe.............................................................................................................................48
Temporary index............................................................................................................................. 50
Temporary index scan............................................................................................................... 50
Temporary index probe............................................................................................................. 52
Temporary buffer............................................................................................................................ 53
Buffer scan.................................................................................................................................53
Queue.............................................................................................................................................. 54
Enqueue.....................................................................................................................................55
Dequeue.................................................................................................................................... 56
Array unnest temporary table........................................................................................................ 57

iii
Array unnest temporary table scan.......................................................................................... 58
Temporary Indexed List..................................................................................................................58
Temporary Indexed List scan and Index Merge....................................................................... 59
Window............................................................................................................................................61
Window scan............................................................................................................................. 62
Objects processed in parallel...............................................................................................................62
Spreading data automatically.............................................................................................................. 63
Processing queries: Overview................................................................................................................... 63
Query optimizer.................................................................................................................................... 64
Query optimization tips........................................................................................................................ 64
Access plan validation..........................................................................................................................65
Single table optimization......................................................................................................................65
Solid State Drives................................................................................................................................. 66
Memory preference controls................................................................................................................67
Join optimization.................................................................................................................................. 68
Nested loop join.............................................................................................................................. 68
Join optimization............................................................................................................................ 70
Join order optimization...................................................................................................................71
Full outer join.................................................................................................................................. 72
Join cost & index selection............................................................................................................. 73
Transitive closure predicates......................................................................................................... 74
LPG.................................................................................................................................................. 74
CQE Join performance tips............................................................................................................. 75
Multiple join types...........................................................................................................................75
Join performance problems........................................................................................................... 76
Join performance tips.....................................................................................................................77
Distinct optimization............................................................................................................................ 78
Grouping optimization..........................................................................................................................79
Hash grouping................................................................................................................................. 79
Index grouping................................................................................................................................ 80
Whole table COUNT(*) grouping.....................................................................................................82
Eliminate grouping columns........................................................................................................... 83
Add grouping columns.................................................................................................................... 83
Index skip key processing.............................................................................................................. 83
Read trigger considerations............................................................................................................85
Grouping set optimization.............................................................................................................. 85
Ordering optimization...........................................................................................................................86
View implementation........................................................................................................................... 87
View composite...............................................................................................................................88
View materialization....................................................................................................................... 88
MQT optimization................................................................................................................................. 89
MQT supported function................................................................................................................. 90
Using MQTs......................................................................................................................................91
MQT examples................................................................................................................................ 92
MQT matching................................................................................................................................. 94
Determining MQT usage................................................................................................................. 97
MQT recommendations.................................................................................................................. 98
Recursive query optimization.............................................................................................................. 98
Example.......................................................................................................................................... 99
Multiple initialization & iterative fullselects.................................................................................101
Predicate pushing......................................................................................................................... 103
SEARCH considerations................................................................................................................103
CYCLE considerations...................................................................................................................104
SMP & recursive queries...............................................................................................................105
System-period temporal tables......................................................................................................... 108
Adaptive Query Processing................................................................................................................ 109
How AQP works............................................................................................................................ 110
AQP example................................................................................................................................ 110

iv
AQP join order...............................................................................................................................111
Database Monitor additions......................................................................................................... 112
Row and column access control........................................................................................................ 114
Indexing strategy and RCAC.........................................................................................................114
Materialized query tables and RCAC............................................................................................ 117
Tools.........................................................................................................................................................121
Health Center..................................................................................................................................... 121
Navigator view.............................................................................................................................. 121
SQL procedures............................................................................................................................ 121
Health_Database_Overview....................................................................................................121
Health_Activity........................................................................................................................126
Health_Design_Limits.............................................................................................................131
Health_Size_Limits..................................................................................................................134
Health_Environmental_Limits................................................................................................ 138
Reset_Environmental_Limits................................................................................................. 142
Database Monitor............................................................................................................................... 143
Start...............................................................................................................................................144
End................................................................................................................................................ 147
Performance rows.........................................................................................................................149
Examples...................................................................................................................................... 149
Application with table scans...................................................................................................149
Queries with table scans.........................................................................................................150
Table scan detail..................................................................................................................... 151
Additional examples............................................................................................................... 152
Navigator monitors.............................................................................................................................154
Start...............................................................................................................................................154
Analyze data................................................................................................................................. 156
Compare data............................................................................................................................... 157
View statements........................................................................................................................... 158
Import........................................................................................................................................... 158
Index advisor......................................................................................................................................158
Index advice and OR predicates.................................................................................................. 159
Index advice for Encoded Vector Index RRN Probe Plans.......................................................... 161
Display information.......................................................................................................................161
System table............................................................................................................................162
Column descriptions.....................................................................................................................164
Database monitor view.................................................................................................................165
Condense advice...........................................................................................................................166
Visual Explain..................................................................................................................................... 166
Start...............................................................................................................................................166
Information available................................................................................................................... 167
Adaptive Query Processing in VE................................................................................................. 169
SQL Plan Cache.................................................................................................................................. 170
Show Statements..........................................................................................................................171
Column descriptions.....................................................................................................................174
Properties..................................................................................................................................... 175
Creating snapshots....................................................................................................................... 182
Event monitor............................................................................................................................... 184
SQL stored procedures................................................................................................................. 184
Clear SQL plan cache procedure.................................................................................................. 184
Verify performance.............................................................................................................................185
View debug messages........................................................................................................................185
Print SQL Information........................................................................................................................ 186
Tool comparison................................................................................................................................. 187
SQL Error Logging Facility (SELF).......................................................................................................187
Change query attributes.................................................................................................................... 192
QAQQINI....................................................................................................................................... 192
CHGQRYA................................................................................................................................ 194

v
Creating the QAQQINI query options file............................................................................... 194
QAQQINI override support..................................................................................................... 194
File format............................................................................................................................... 195
Update..................................................................................................................................... 195
Authority requirements...........................................................................................................195
System-supplied triggers........................................................................................................196
Query options.......................................................................................................................... 196
SQL_XML_DATA_CCSID option.............................................................................................. 210
Query Supervisor................................................................................................................................211
Using Query Supervisor to monitor query resource usage..........................................................212
Query Supervisor configuration and operation............................................................................212
Managing Query Supervisor activity.............................................................................................213
Using DETECTION_FREQUENCY to protect system resources................................................... 214
Writing a Query Supervisor Exit Program.....................................................................................215
Query Supervisor example exit programs....................................................................................216
Exit program to send message to QSYSOPR.......................................................................... 216
Exit program to end query...................................................................................................... 220
Exit program to dump plan cache information for query....................................................... 223
Exit program to log information using a data queue.............................................................. 226
Predictive Query Governor.................................................................................................................242
How to use.................................................................................................................................... 243
Cancel a query.............................................................................................................................. 244
Control the reply........................................................................................................................... 244
Test performance..........................................................................................................................245
Time limit examples..................................................................................................................... 245
Test temporary storage use..........................................................................................................246
Storage limit examples................................................................................................................. 246
Parallel processing............................................................................................................................. 247
System-wide................................................................................................................................. 247
Job level........................................................................................................................................ 248
Statistics manager..............................................................................................................................249
Automatic collection.....................................................................................................................250
Automatic refresh......................................................................................................................... 251
View requests............................................................................................................................... 251
Indexes and column statistics..................................................................................................... 251
Background collection.................................................................................................................. 253
View column statistics..................................................................................................................253
Manual collection and refresh ..................................................................................................... 253
APIs...............................................................................................................................................255
Display MQT columns.........................................................................................................................255
Check pending constraints................................................................................................................ 257
Limiting temporary storage and CPU used by queries...................................................................... 258
Creating an index strategy.......................................................................................................................259
Binary radix indexes...........................................................................................................................259
Derived key index......................................................................................................................... 259
Sparse indexes..............................................................................................................................259
Optimization............................................................................................................................ 260
Matching algorithm................................................................................................................. 261
Sparse index examples........................................................................................................... 263
Specify PAGESIZE.........................................................................................................................265
Index maintenance.......................................................................................................................266
Encoded vector indexes..................................................................................................................... 266
How the EVI works....................................................................................................................... 267
When to create..............................................................................................................................268
Maintenance................................................................................................................................. 270
Recommendations........................................................................................................................272
Compare radix & EVIs........................................................................................................................ 275
Indexes & the optimizer.....................................................................................................................275

vi
Index not used.............................................................................................................................. 275
Display indexes for a table........................................................................................................... 276
Determine unnecessary indexes.................................................................................................. 280
Reset usage counts.......................................................................................................................280
View index builds..........................................................................................................................281
Manage index rebuilds..................................................................................................................281
Indexing strategy............................................................................................................................... 286
Reactive approach........................................................................................................................ 287
Proactive approach.......................................................................................................................287
Coding for effective indexes...............................................................................................................288
Avoid numeric conversions.......................................................................................................... 288
Avoid arithmetic expressions....................................................................................................... 288
Avoid character string padding.................................................................................................... 289
LIKE considerations......................................................................................................................289
Derived indexes............................................................................................................................ 290
Sparse indexes..............................................................................................................................291
Indexes with sort sequence...............................................................................................................291
Selection, joins, or grouping......................................................................................................... 291
Ordering........................................................................................................................................ 292
Index examples..................................................................................................................................292
Equal selection, no sort sequence............................................................................................... 292
Equal selection, unique-weight sort sequence........................................................................... 292
Equal selection, shared-weight sort sequence........................................................................... 293
Greater than selection, unique-weight sort sequence................................................................ 293
Join selection, unique-weight sort sequence..............................................................................293
Join selection, shared-weight sort sequence..............................................................................293
Order, no sort sequence............................................................................................................... 294
Order, unique-weight sort sequence........................................................................................... 294
Order, shared-weight sort sequence............................................................................................294
Order, ALWCPYDTA(*OPTIMIZE), unique-weight sort sequence................................................295
Group, no sort sequence.............................................................................................................. 295
Group, unique-weight sort sequence...........................................................................................295
Group, shared-weight sort sequence...........................................................................................295
Order & group on same columns, unique-weight sort sequence................................................296
Order & group on same columns, ALWCPYDTA(*OPTIMIZE), unique-weight sort sequence....296
Order & group on same columns, shared-weight sort sequence................................................297
Order & group on same columns, ALWCPYDTA(*OPTIMIZE), shared-weight sort sequence.... 297
Order & group on different columns, unique-weight sort sequence.......................................... 297
Order & group on different columns, ALWCPYDTA(*OPTIMIZE), unique-weight sort
sequence................................................................................................................................. 298
Order & group on different columns, ALWCPYDTA(*OPTIMIZE), shared-weight sort
sequence................................................................................................................................. 298
Sparse index examples.................................................................................................................298
Application design tips............................................................................................................................ 301
Live data............................................................................................................................................. 301
Reduce open operations.................................................................................................................... 302
Retain cursor positions...................................................................................................................... 305
Non-ILE program calls..................................................................................................................305
ILE program calls..........................................................................................................................305
General rules.................................................................................................................................306
Programming techniques........................................................................................................................ 307
Use the OPTIMIZE clause.................................................................................................................. 307
Use FETCH FOR n ROWS....................................................................................................................308
Improve SQL blocking performance............................................................................................ 309
Use INSERT n ROWS.......................................................................................................................... 309
Control database manager blocking..................................................................................................310
Optimize columns selected............................................................................................................... 311
PREPARE considerations................................................................................................................... 311

vii
REFRESH(*FORWARD) considerations..............................................................................................311
Improve concurrency......................................................................................................................... 312
Use SELECTIVITY to supply missing information............................................................................. 313
Performance considerations................................................................................................................... 315
Long object names............................................................................................................................. 315
Precompile options............................................................................................................................ 315
ALWCPYDTA....................................................................................................................................... 316
VARCHAR and VARGRAPHIC............................................................................................................. 317
Field procedures................................................................................................................................ 319
Examples...................................................................................................................................... 320
Db2 for i Services.....................................................................................................................................321
Application Services...........................................................................................................................322
DELIMIT_NAME scalar function................................................................................................... 322
OVERRIDE_QAQQINI procedure..................................................................................................322
OVERRIDE_TABLE procedure.......................................................................................................323
PARSE_STATEMENT table function..............................................................................................324
SELFCODES global variable.......................................................................................................... 331
SQL_ERROR_LOG view.................................................................................................................331
SQLCODE_INFO table function.................................................................................................... 333
VALIDATE_SELF scalar function...................................................................................................334
WLM_SET_CLIENT_INFO procedure............................................................................................ 335
Performance Services........................................................................................................................ 337
ACT_ON_INDEX_ADVICE procedure........................................................................................... 337
ACTIVE_QUERY_INFO table function.......................................................................................... 338
ADD_QUERY_THRESHOLD procedure.......................................................................................... 341
DATABASE_MONITOR_INFO view............................................................................................... 344
HARVEST_INDEX_ADVICE procedure......................................................................................... 347
MTI_INFO table function..............................................................................................................349
QUERY_SUPERVISOR view...........................................................................................................351
REMOVE_INDEXES procedure..................................................................................................... 352
REMOVE_QUERY_THRESHOLD procedure...................................................................................353
RESET_TABLE_INDEX_STATISTICS procedure........................................................................... 353
Plan Cache Services........................................................................................................................... 355
CHANGE_PLAN_CACHE_SIZE procedure.................................................................................... 355
CLEAR_PLAN_CACHE procedure ................................................................................................ 356
DUMP_PLAN_CACHE procedure...................................................................................................357
DUMP_PLAN_CACHE_PROPERTIES procedure...........................................................................359
DUMP_PLAN_CACHE_TOPN procedure....................................................................................... 360
DUMP_SNAP_SHOT_PROPERTIES procedure..............................................................................361
END_ALL_PLAN_CACHE_EVENT_MONITORS procedure........................................................... 361
END_PLAN_CACHE_EVENT_MONITOR procedure......................................................................362
IMPORT_PC_EVENT_MONITOR procedure................................................................................. 362
IMPORT_PC_SNAPSHOT procedure............................................................................................ 363
REMOVE_PC_EVENT_MONITOR procedure................................................................................ 363
REMOVE_PC_SNAPSHOT procedure........................................................................................... 364
REMOVE_PERFORMANCE_MONITOR procedure........................................................................364
START_PLAN_CACHE_EVENT_MONITOR procedure.................................................................. 364
Utility Services....................................................................................................................................365
ANALYZE_CATALOG table function.............................................................................................. 365
CANCEL_SQL procedure...............................................................................................................367
CHECK_SYSCST procedure.......................................................................................................... 368
CHECK_SYSROUTINE procedure................................................................................................. 369
COMPARE_FILE table function.....................................................................................................371
DUMP_SQL_CURSORS procedure................................................................................................ 373
END_IDLE_SQE_THREADS procedure ........................................................................................ 374
EXTRACT_STATEMENTS procedure............................................................................................. 375
FIND_AND_CANCEL_QSQSRVR_SQL procedure......................................................................... 376
FIND_QSQSRVR_JOBS procedure............................................................................................... 377

viii
GENERATE_SQL procedure.......................................................................................................... 378
GENERATE_SQL_OBJECTS procedure.........................................................................................387
RELATED_OBJECTS table function...............................................................................................398
RESTART_IDENTITY procedure................................................................................................... 401
SWAP_DYNUSRPRF procedure.................................................................................................... 401
SYSFILES view.............................................................................................................................. 402
SYSMEMBERSTAT view.................................................................................................................413
VALIDATE_DATA, VALIDATE_DATA_FILE, and VALIDATE_DATA_LIBRARY table functions......416
IBM i Services.......................................................................................................................................... 417
Application Services...........................................................................................................................418
ACTIVATION_GROUP_INFO table function..................................................................................418
ADD_USER_INDEX_ENTRY and ADD_USER_INDEX_ENTRY_BINARY procedures................... 420
BINDING_DIRECTORY_INFO view.............................................................................................. 421
BOUND_MODULE_INFO view.......................................................................................................422
BOUND_SRVPGM_INFO view.......................................................................................................431
CHANGE_USER_SPACE and CHANGE_USER_SPACE_BINARY procedures............................... 432
CHANGE_USER_SPACE_ATTRIBUTES procedure.......................................................................433
CLEAR_DATA_QUEUE procedure................................................................................................. 434
COMMAND_INFO view................................................................................................................. 436
CREATE_USER_INDEX procedure................................................................................................443
CREATE_USER_SPACE procedure................................................................................................446
DATA_AREA_INFO table function................................................................................................ 449
DATA_AREA_INFO view............................................................................................................... 450
DATA_QUEUE_ENTRIES table function....................................................................................... 452
DATA_QUEUE_INFO view............................................................................................................. 454
DB_TRANSACTION_INFO view.................................................................................................... 457
DB_TRANSACTION_JOURNAL_INFO table function...................................................................475
DB_TRANSACTION_OBJECT_INFO table function...................................................................... 477
DB_TRANSACTION_RECORD_INFO table function.....................................................................478
ENVIRONMENT_VARIABLE_INFO view....................................................................................... 480
ERRNO_INFO scalar function.......................................................................................................481
EXIT_POINT_INFO view............................................................................................................... 482
EXIT_PROGRAM_INFO view........................................................................................................ 484
GENERATE_SPREADSHEET scalar function................................................................................ 485
GETENV scalar function................................................................................................................487
LPRINTF procedure...................................................................................................................... 488
PROGRAM_EXPORT_IMPORT_INFO view................................................................................... 488
PROGRAM_INFO view.................................................................................................................. 490
PUTENV scalar function................................................................................................................504
QCMDEXC procedure....................................................................................................................505
QCMDEXC scalar function............................................................................................................ 505
RECEIVE_DATA_QUEUE table function........................................................................................505
REMOVE_USER_INDEX_ENTRY and REMOVE_USER_INDEX_ENTRY_BINARY table
functions.................................................................................................................................. 508
SEND_DATA_QUEUE, SEND_DATA_QUEUE_BINARY, and SEND_DATA_QUEUE_UTF8
procedures...............................................................................................................................510
SEND_EMAIL scalar function....................................................................................................... 511
SERVICES_INFO table.................................................................................................................. 512
SET_PASE_SHELL_INFO procedure.............................................................................................515
SPLIT table function..................................................................................................................... 516
STACK_INFO table function......................................................................................................... 517
USER_INDEX_ENTRIES table function........................................................................................522
USER_INDEX_INFO view............................................................................................................. 523
USER_SPACE table function......................................................................................................... 524
USER_SPACE_INFO view............................................................................................................. 525
WATCH_DETAIL table function.................................................................................................... 526
WATCH_INFO view....................................................................................................................... 531
Backup and Recovery Services.......................................................................................................... 533

ix
Backup, Recovery, and Media Services (BRMS) Services............................................................533
MEDIA_LIBRARY_INFO view....................................................................................................... 533
SAVE_FILE_INFO view................................................................................................................. 536
SAVE_FILE_OBJECTS table function........................................................................................... 538
SAVE_FILE_OBJECTS view...........................................................................................................541
TAPE_CARTRIDGE_INFO view..................................................................................................... 542
Communication Services................................................................................................................... 544
ACTIVE_DB_CONNECTIONS table function.................................................................................544
ADD_TIME_SERVER procedure.................................................................................................... 547
CHANGE_OBJECTCONNECT procedure.......................................................................................548
DNS_LOOKUP table function........................................................................................................551
DNS_LOOKUP_IP scalar function................................................................................................. 552
ENV_SYS_INFO view.....................................................................................................................552
HTTP_SERVER_INFO view............................................................................................................553
NETSTAT_INFO view.....................................................................................................................554
NETSTAT_INTERFACE_INFO view............................................................................................... 561
NETSTAT_JOB_INFO view............................................................................................................ 568
NETSTAT_ROUTE_INFO view....................................................................................................... 570
NETWORK_ATTRIBUTE_INFO view............................................................................................ 577
OBJECTCONNECT_INFO view......................................................................................................584
PING table function...................................................................................................................... 585
RDB_ENTRY_INFO view............................................................................................................... 588
REMOVE_TIME_SERVER procedure.............................................................................................591
SERVER_SBS_CONFIGURATION view......................................................................................... 591
SERVER_SBS_ROUTING view...................................................................................................... 592
SET_SERVER_SBS_ROUTING procedure.....................................................................................595
TCPIP_INFO view..........................................................................................................................601
TIME_PROTOCOL_INFO view...................................................................................................... 602
Configuration Services....................................................................................................................... 602
HARDWARE_RESOURCE_INFO table function............................................................................602
HARDWARE_RESOURCE_INFO view........................................................................................... 609
IFS Services........................................................................................................................................615
COMPARE_IFS table function...................................................................................................... 615
IFS_JOB_INFO table function...................................................................................................... 617
IFS_OBJECT_LOCK_INFO table function.....................................................................................621
IFS_OBJECT_PRIVILEGES table function....................................................................................624
IFS_OBJECT_REFERENCES_INFO table function....................................................................... 626
IFS_OBJECT_STATISTICS table function..................................................................................... 629
IFS_READ, IFS_READ_BINARY, and IFS_READ_UTF8 table functions...................................... 641
IFS_RENAME scalar function....................................................................................................... 643
IFS_UNLINK scalar function.........................................................................................................644
IFS_WRITE, IFS_WRITE_BINARY, and IFS_WRITE_UTF8 procedures...................................... 645
SERVER_SHARE_INFO view.........................................................................................................647
Java Services......................................................................................................................................650
JVM_INFO table function............................................................................................................. 650
JVM_INFO view............................................................................................................................ 652
SET_JVM procedure......................................................................................................................653
Journal Services................................................................................................................................. 654
ASSOCIATE_JOURNAL_RECEIVER table function...................................................................... 654
AUDIT_JOURNAL_DATA_MART_INFO view................................................................................ 657
Audit journal entry services..........................................................................................................658
AUDIT JOURNAL table function common information.......................................................... 658
AUDIT_JOURNAL_AD table function......................................................................................662
AUDIT_JOURNAL_AF table function...................................................................................... 671
AUDIT_JOURNAL_AP table function...................................................................................... 674
AUDIT_JOURNAL_AU table function......................................................................................675
AUDIT_JOURNAL_AX table function...................................................................................... 676
AUDIT_JOURNAL_CA table function...................................................................................... 678

x
AUDIT_JOURNAL_CD table function...................................................................................... 683
AUDIT_JOURNAL_CO table function...................................................................................... 684
AUDIT_JOURNAL_CP table function...................................................................................... 685
AUDIT_JOURNAL_DO table function......................................................................................696
AUDIT_JOURNAL_DS table function...................................................................................... 697
AUDIT_JOURNAL_EV table function...................................................................................... 711
AUDIT_JOURNAL_GR table function...................................................................................... 712
AUDIT_JOURNAL_IM table function...................................................................................... 715
AUDIT_JOURNAL_JS table function.......................................................................................718
AUDIT_JOURNAL_LD table function...................................................................................... 722
AUDIT_JOURNAL_M0 table function..................................................................................... 723
AUDIT_JOURNAL_M6 table function..................................................................................... 725
AUDIT_JOURNAL_M7 table function..................................................................................... 731
AUDIT_JOURNAL_M8 table function..................................................................................... 733
AUDIT_JOURNAL_M9 table function..................................................................................... 738
AUDIT_JOURNAL_NA table function......................................................................................739
AUDIT_JOURNAL_OM table function..................................................................................... 740
AUDIT_JOURNAL_OR table function...................................................................................... 742
AUDIT_JOURNAL_OW table function..................................................................................... 745
AUDIT_JOURNAL_PA table function...................................................................................... 746
AUDIT_JOURNAL_PF table function...................................................................................... 748
AUDIT_JOURNAL_PG table function......................................................................................753
AUDIT_JOURNAL_PS table function...................................................................................... 757
AUDIT_JOURNAL_PU table function...................................................................................... 759
AUDIT_JOURNAL_PW table function..................................................................................... 760
AUDIT_JOURNAL_RA table function...................................................................................... 762
AUDIT_JOURNAL_RO table function......................................................................................764
AUDIT_JOURNAL_RZ table function...................................................................................... 765
AUDIT_JOURNAL_SK table function...................................................................................... 766
AUDIT_JOURNAL_SM table function......................................................................................768
AUDIT_JOURNAL_ST table function.......................................................................................775
AUDIT_JOURNAL_SV table function...................................................................................... 779
AUDIT_JOURNAL_ZC table function...................................................................................... 780
AUDIT_JOURNAL_ZR table function...................................................................................... 782
DISPLAY_JOURNAL table function...............................................................................................784
JOURNAL_INFO view................................................................................................................... 798
JOURNAL_RECEIVER_INFO view................................................................................................ 806
JOURNALED_OBJECTS view........................................................................................................ 815
MANAGE_AUDIT_JOURNAL_DATA_MART procedure................................................................ 817
REMOTE_JOURNAL_INFO view................................................................................................... 819
SMAPP_ACCESS_PATHS view...................................................................................................... 825
Librarian Services...............................................................................................................................826
JOURNAL_INHERIT_RULES view................................................................................................ 826
LIBRARY_INFO table function......................................................................................................830
LIBRARY_LIST_INFO view............................................................................................................833
OBJECT_STATISTICS table function............................................................................................ 834
SYSTEM_OBJECT_TYPES table.................................................................................................... 841
Message Handling Services............................................................................................................... 842
HISTORY_LOG_INFO table function............................................................................................ 842
JOBLOG_INFO table function...................................................................................................... 847
MESSAGE_FILE_DATA view......................................................................................................... 849
MESSAGE_QUEUE_INFO table function...................................................................................... 852
MESSAGE_QUEUE_INFO view..................................................................................................... 855
REPLY_INQUIRY_MESSAGES scalar function..............................................................................856
REPLY_LIST_INFO view................................................................................................................857
SEND_MESSAGE procedure ........................................................................................................ 858
Performance Services........................................................................................................................ 859
COLLECTION_SERVICES_INFO view........................................................................................... 859

xi
PowerHA Services.............................................................................................................................. 862
Product Services................................................................................................................................ 862
CHECK_PRODUCT_OPTIONS table function............................................................................... 863
LICENSE_EXPIRATION_CHECK procedure................................................................................. 864
LICENSE_INFO view.....................................................................................................................865
SOFTWARE_PRODUCT_INFO view.............................................................................................. 867
PTF Services....................................................................................................................................... 872
DEFECTIVE_PTF_CURRENCY view...............................................................................................872
ELECTRONIC_SERVICE_AGENT_INFO view................................................................................873
FIRMWARE_CURRENCY view.......................................................................................................874
GROUP_PTF_CURRENCY view...................................................................................................... 877
GROUP_PTF_DETAILS view.......................................................................................................... 878
GROUP_PTF_INFO view................................................................................................................882
PTF_COVER_LETTER table function.............................................................................................883
PTF_INFO view............................................................................................................................. 884
Security Services................................................................................................................................887
AUTHORITY_COLLECTION views................................................................................................. 888
AUTHORIZATION_LIST_INFO view............................................................................................. 888
AUTHORIZATION_LIST_USER_INFO view.................................................................................. 890
CERTIFICATE_INFO table function..............................................................................................892
CHANGE_USER_PROFILE table function.....................................................................................895
DRDA_AUTHENTICATION_ENTRY_INFO view............................................................................898
FUNCTION_INFO view................................................................................................................. 899
FUNCTION_USAGE view.............................................................................................................. 901
GROUP_PROFILE_ENTRIES view.................................................................................................901
OBJECT_OWNERSHIP view.......................................................................................................... 901
OBJECT_PRIVILEGES table function........................................................................................... 904
OBJECT_PRIVILEGES view.......................................................................................................... 907
SECURITY_INFO view.................................................................................................................. 910
SET_COLUMN_ATTRIBUTE procedure.........................................................................................913
SPECIAL_AUTHORITY_DATA_MART table.................................................................................. 914
SQL_CHECK_AUTHORITY scalar function................................................................................... 915
SQL_CHECK_FUNCTION_USAGE scalar function....................................................................... 916
SQL_CHECK_SPECIAL_AUTHORITY scalar function.................................................................. 916
USER_INFO view.......................................................................................................................... 917
USER_INFO_BASIC view..............................................................................................................926
Spool Services.................................................................................................................................... 934
DELETE_OLD_SPOOLED_FILES procedure.................................................................................. 934
GENERATE_PDF scalar function.................................................................................................. 936
OUTPUT_QUEUE_ENTRIES table function.................................................................................. 937
OUTPUT_QUEUE_ENTRIES view..................................................................................................941
OUTPUT_QUEUE_ENTRIES_BASIC view..................................................................................... 946
OUTPUT_QUEUE_INFO view........................................................................................................ 948
PRINTER_FILE_INFO view...........................................................................................................954
SPOOLED_FILE_DATA table function...........................................................................................956
SPOOLED_FILE_INFO table function...........................................................................................957
Storage Services.................................................................................................................................961
ADD_DEVICE_LOCKING_POLICY procedure...............................................................................962
ASP_INFO view............................................................................................................................. 962
ASP_JOB_INFO view.....................................................................................................................971
ASP_VARY_INFO view...................................................................................................................972
CHANGE_DEVICE_LOCKING_POLICY procedure....................................................................... 974
CHANGE_DISK_PATHS procedure...............................................................................................974
CREATE_LOCKING_POLICY procedure....................................................................................... 977
DELETE_LOCKING_POLICY procedure........................................................................................977
FACTORY_RESET_DEVICE procedure.......................................................................................... 978
LOCKING_POLICY_INFO view..................................................................................................... 978
NVME_INFO view......................................................................................................................... 979

xii
REMOVE_DEVICE_LOCKING_POLICY procedure....................................................................... 983
SYSDISKSTAT table function........................................................................................................ 983
SYSDISKSTAT view....................................................................................................................... 988
SYSTMPSTG view.......................................................................................................................... 995
UNLOCK_DEVICE procedure........................................................................................................ 996
USER_STORAGE view................................................................................................................... 997
System Health Services..................................................................................................................... 997
System limit alerts......................................................................................................................1000
SYSLIMTBL table........................................................................................................................ 1001
SYSLIMITS view..........................................................................................................................1003
SYSLIMITS_BASIC view............................................................................................................. 1006
PROCESS_SYSTEM_LIMITS_ALERTS procedure.......................................................................1007
QIBM_SYSTEM_LIMITS global variables...................................................................................1008
Work Management Services............................................................................................................ 1009
ACTIVE_JOB_INFO table function.............................................................................................1009
ADD_TRACKED_JOB_QUEUE procedure.................................................................................... 1026
Submitted Job Tracker..........................................................................................................1027
AUTOSTART_JOB_INFO view.....................................................................................................1029
CLEAR_TRACKED_JOB_INFO procedure...................................................................................1030
COMMUNICATIONS_ENTRY_INFO view....................................................................................1032
ENDED_JOB_INFO table function..............................................................................................1034
GET_JOB_INFO table function...................................................................................................1037
JOB_DESCRIPTION_INFO view.................................................................................................1039
JOB_INFO table function........................................................................................................... 1046
JOB_LOCK_INFO table function................................................................................................ 1058
JOB_QUEUE_ENTRIES view.......................................................................................................1061
JOB_QUEUE_INFO view............................................................................................................. 1071
MEMORY_POOL table function.................................................................................................. 1075
MEMORY_POOL_INFO view.......................................................................................................1077
OBJECT_LOCK_INFO view......................................................................................................... 1079
OPEN_FILES table function....................................................................................................... 1081
PRESTART_JOB_INFO view........................................................................................................1083
PRESTART_JOB_STATISTICS table function............................................................................. 1086
RECORD_LOCK_INFO view........................................................................................................ 1089
REMOVE_TRACKED_JOB_QUEUE procedure............................................................................ 1090
ROUTING_ENTRY_INFO view.................................................................................................... 1091
SCHEDULED_JOB_INFO view.................................................................................................... 1093
SUBSYSTEM_INFO view.............................................................................................................1096
SUBSYSTEM_POOL_INFO view................................................................................................. 1098
SYSTEM_ACTIVITY_INFO table function.................................................................................. 1099
SYSTEM_STATUS table function................................................................................................ 1100
SYSTEM_STATUS_INFO view..................................................................................................... 1110
SYSTEM_STATUS_INFO_BASIC view.........................................................................................1118
SYSTEM_VALUE_INFO view....................................................................................................... 1125
TRACKED_JOB_INFO table function..........................................................................................1126
TRACKED_JOB_QUEUES view.................................................................................................... 1135
WORKLOAD_GROUP_INFO view................................................................................................ 1136
WORKSTATION_INFO view........................................................................................................1137
SYSTOOLS.............................................................................................................................................. 1138
Using SYSTOOLS.............................................................................................................................. 1138
SYSTOOLS Services..........................................................................................................................1140
HTTP function overview...................................................................................................................1141
BASE64DECODE scalar function................................................................................................1146
BASE64ENCODE scalar function................................................................................................1147
HTTPBLOB and HTTPCLOB scalar functions............................................................................. 1147
HTTPBLOBVERBOSE and HTTPCLOBVERBOSE table functions...............................................1148
HTTPDELETEBLOB and HTTPDELETECLOB scalar functions................................................... 1149
HTTPDELETEBLOBVERBOSE and HTTPDELETECLOBVERBOSE table functions..................... 1150

xiii
HTTPGETBLOB and HTTPGETCLOB scalar functions................................................................1150
HTTPGETBLOBVERBOSE and HTTPGETCLOBVERBOSE table functions................................. 1151
HTTPHEAD scalar function........................................................................................................ 1152
HTTPPOSTBLOB and HTTPPOSTCLOB scalar functions........................................................... 1152
HTTPPOSTBLOBVERBOSE and HTTPPOSTCLOBVERBOSE table functions.............................1153
HTTPPUTBLOB and HTTPPUTCLOB scalar functions............................................................... 1153
HTTPPUTBLOBVERBOSE and HTTPPUTCLOBVERBOSE table functions................................. 1154
URLDECODE scalar function...................................................................................................... 1155
URLENCODE scalar function...................................................................................................... 1155
Database monitor formats.................................................................................................................... 1155
SQL table.......................................................................................................................................... 1155
SQL view........................................................................................................................................... 1161
1000 - SQL Information............................................................................................................. 1161
3000 - Table Scan.......................................................................................................................1181
3001 - Index Used......................................................................................................................1185
3002 - Index Created................................................................................................................. 1191
3003 - Query Sort.......................................................................................................................1197
3004 - Temp Table..................................................................................................................... 1201
3005 - Table Locked...................................................................................................................1207
3006 - Access Plan Rebuilt........................................................................................................ 1209
3007 - Optimizer Timed Out...................................................................................................... 1213
3008 - Subquery Processing......................................................................................................1218
3010 - Host Variable, ODP Implementation..............................................................................1219
3011 - Array Host Variables.......................................................................................................1220
3012 - Global Variables..............................................................................................................1222
3014 - Generic QQ Information................................................................................................. 1223
3015 - Statistics Information.....................................................................................................1233
3018 - STRDBMON/ENDDBMON............................................................................................... 1235
3019 - Rows retrieved................................................................................................................1238
3020 - Index advised (SQE)....................................................................................................... 1240
3021 - Bitmap Created...............................................................................................................1243
3022 - Bitmap Merge................................................................................................................. 1245
3023 - Temp Hash Table Created.............................................................................................. 1248
3025 - Distinct Processing......................................................................................................... 1251
3026 - Set operation.................................................................................................................. 1253
3027 - Subquery Merge............................................................................................................. 1255
3028 - Grouping......................................................................................................................... 1259
3030 - Materialized query tables...............................................................................................1262
3031 - Recursive common table expressions........................................................................... 1265
Messages reference.............................................................................................................................. 1267
Performance information.................................................................................................................1267
Open data paths...............................................................................................................................1292
PRTSQLINF.......................................................................................................................................1298

Notices............................................................................................................1313
Programming interface information......................................................................................................1314
Trademarks............................................................................................................................................1314
Terms and conditions............................................................................................................................ 1315

xiv
Database performance and query optimization
The goal of database performance tuning is to minimize the response time of your queries by making the
best use of your system resources. The best use of these resources involves minimizing network traffic,
disk I/O, and CPU time. This goal can only be achieved by understanding the logical and physical structure
of your data, the applications used on your system, and how the conflicting uses of your database might
affect performance.
The best way to avoid performance problems is to ensure that performance issues are part of your
ongoing development activities. Many of the most significant performance improvements are realized
through careful design at the beginning of the database development cycle. To most effectively optimize
performance, you must identify the areas that yield the largest performance increases over the widest
variety of situations. Focus your analysis on these areas.
Many of the examples within this publication illustrate a query written through either an SQL or an
OPNQRYF query interface. The interface chosen for a particular example does not indicate an operation
exclusive to that query interface, unless explicitly noted. It is only an illustration of one possible query
interface. Most examples can be easily rewritten into whatever query interface that you prefer.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 1311.

What's new for IBM i 7.4


The following information was added or updated in the initial release of IBM i 7.4:
• Support for managing temporary storage and CPU usage was added : “Limiting temporary storage and
CPU used by queries” on page 258
• Plan cache sizing was updated : “Plan cache” on page 16
• Plan cache properties was updated : “SQL plan cache properties” on page 175
• Support for whole table COUNT(*) grouping was added : “Whole table COUNT(*) grouping
implementation” on page 82
• Database monitor records that have additions in 7.4:
– “Database monitor view 3010 - Host Variable & ODP Implementation” on page 1219
• New services
– ASP_JOB_INFO view: “ASP_JOB_INFO view” on page 971
– DATA_AREA_INFO view and table function: “DATA_AREA_INFO view” on page 450,
“DATA_AREA_INFO table function” on page 449
– FIRMWARE_CURRENCY view: “FIRMWARE_CURRENCY view” on page 874
– MESSAGE_FILE_DATA view: “MESSAGE_FILE_DATA view” on page 849
– SPLIT table function: “SPLIT table function” on page 516
– SPOOLED_FILE_DATA table function: “SPOOLED_FILE_DATA table function” on page 956
– Add, remove, and view Network Time Protocol servers: “ADD_TIME_SERVER procedure” on page 547,
“REMOVE_TIME_SERVER procedure” on page 591, “TIME_PROTOCOL_INFO view” on page 602
– The HTTP functions in SYSTOOLS have been documented: “HTTP function overview” on page 1141
• Updated services
– The maximum table size has been added as a tracked system limit and as a limit that sends alerts:
“System Health Services” on page 997, “System limit alerts” on page 1000
– ASP_INFO returns the relational database name for SYSBASE: “ASP_INFO view” on page 962
– GET_JOB_INFO returns additional columns: “GET_JOB_INFO table function” on page 1037

© Copyright IBM Corp. 1998, 2019 1


– JOB_DESCRIPTION_INFO returns workload group: “JOB_DESCRIPTION_INFO view” on page 1039
– JOBLOG_INFO table function returns the message key: “JOBLOG_INFO table function” on page 847
– OBJECT_PRIVILEGES view returns authorization list: “OBJECT_PRIVILEGES view” on page 907
– OBJECT_STATISTICS table function returns IASP name and the authority collection value:
“OBJECT_STATISTICS table function” on page 834
– PARSE_STATEMENT table function returns information for DROP statements and foreign key
constraints: “PARSE_STATEMENT table function” on page 324
– SET_SERVER_SBS_ROUTING and SERVER_SBS_ROUTING support QDBMSRVR:
“SET_SERVER_SBS_ROUTING procedure” on page 595, “SERVER_SBS_ROUTING view” on page 592
– WLM_SET_CLIENT_INFO procedure uses defaults for unspecified parameters:
“WLM_SET_CLIENT_INFO procedure” on page 335

What's new since the first 7.4 publication


The following revisions or additions have been made to the Performance and query optimization
documentation since the first 7.4 publication:
• June 2024 update
– New services
- AUDIT_JOURNAL_DATA_MART_INFO view and MANAGE_AUDIT_JOURNAL_DATA_MART
provide a way to gather audit journal information for efficient
query access: “AUDIT_JOURNAL_DATA_MART_INFO view” on page 657 and
“MANAGE_AUDIT_JOURNAL_DATA_MART procedure” on page 817
- AUDIT_JOURNAL_NA and AUDIT_JOURNAL_PS table functions return entry specific data:
“AUDIT_JOURNAL_NA table function” on page 739 and “AUDIT_JOURNAL_PS table function” on
page 757
- CHECK_PRODUCT_OPTIONS table function returns formatted information generated by the Check
Product Option (CHKPRDOPT) CL command: “CHECK_PRODUCT_OPTIONS table function” on page
863
- COMPARE_IFS table function compares objects or directories in the Integrated File System (IFS):
“COMPARE_IFS table function” on page 615
- DB_TRANSACTION_OBJECT_INFO table function returns information about objects under
commitment control for a transaction: “DB_TRANSACTION_OBJECT_INFO table function” on page
477
- DB_TRANSACTION_RECORD_INFO table function returns record level information for a transaction:
“DB_TRANSACTION_RECORD_INFO table function” on page 478
- ERRNO_INFO scalar function returns descriptive text for an errno value: “ERRNO_INFO scalar
function” on page 481
- GETENV and PUTENV scalar functions add, change, retrieve the value of an environment variable:
“GETENV scalar function” on page 487 and “PUTENV scalar function” on page 504
- IFS_UNLINK scalar function deletes an IFS file: “IFS_UNLINK scalar function” on page 644
- PRINTER_FILE_INFO view returns information about printer files: “PRINTER_FILE_INFO view” on
page 954
- SPECIAL_AUTHORITY_DATA_MART materialized query table can be used to gather all the special
authorities for all users: “SPECIAL_AUTHORITY_DATA_MART table” on page 914
- SYSMEMBERSTAT view returns statistical information for file members, including program
described files: “SYSMEMBERSTAT view” on page 413
- SYSTEM_OBJECT_TYPES table lists all the type values for system objects:
“SYSTEM_OBJECT_TYPES table” on page 841
– Updated services

2 IBM i: Performance and Query Optimization


- ACTIVE_QUERY_INFO has a filter for the job's user: “ACTIVE_QUERY_INFO table function” on page
338
- CLEAR_TRACKED_JOB_INFO has additional filters to restrict entries to be removed from the job
tracking file: “CLEAR_TRACKED_JOB_INFO procedure” on page 1030
- DUMP_PLAN_CACHE has a filter for Independent ASP name: “DUMP_PLAN_CACHE procedure” on
page 357
- GENERATE_SPREADSHEET generates proportional width columns for xls and xlsx formats:
“GENERATE_SPREADSHEET scalar function” on page 485
- SEND_EMAIL sends an email to multiple users and can include multiple attachments:
“SEND_EMAIL scalar function” on page 511
- SYSDISKSTAT view and table function return an indication of whether all the pages for the disk unit
have been cleared: “SYSDISKSTAT view” on page 988 and “SYSDISKSTAT table function” on page
983
• November 2023 update
– SQL Error Logging Facility (SELF) captures thread information for the job: “SQL_ERROR_LOG view”
on page 331. Support for logging all errors or all warnings has been added: “VALIDATE_SELF scalar
function” on page 334
– System limit alerting is instrumented for the maximum number of deleted rows in a partition limit:
“System limit alerts” on page 1000
– New services
- AUDIT_JOURNAL_AU and AUDIT_JOURNAL_LD table functions return entry specific data:
“AUDIT_JOURNAL_AU table function” on page 675 and “AUDIT_JOURNAL_LD table function” on
page 722
- DB_TRANSACTION_JOURNAL_INFO returns information about journal resources for a transaction:
“DB_TRANSACTION_JOURNAL_INFO table function” on page 475
- ENDED_JOB_INFO returns details about jobs that have ended: “ENDED_JOB_INFO table function”
on page 1034
- GENERATE_SPREADSHEET generates a spreadsheet from a table or query:
“GENERATE_SPREADSHEET scalar function” on page 485
- IFS_RENAME renames an IFS file or directory: “IFS_RENAME scalar function” on page 643
- JOB_QUEUE_ENTRIES returns a list of entries in a job queue: “JOB_QUEUE_ENTRIES view” on
page 1061
- PING checks connectivity to another system: “PING table function” on page 585
- PTF_COVER_LETTER returns the content of a cover letter: “PTF_COVER_LETTER table function” on
page 883
- REPLY_INQUIRY_MESSAGES sends a reply to one or more QSYSOPR inquiry messages:
“REPLY_INQUIRY_MESSAGES scalar function” on page 856
- SEND_EMAIL sends an email to a user: “SEND_EMAIL scalar function” on page 511
- SQLCODE_INFO returns message information that corresponds to a specific SQLCODE:
“SQLCODE_INFO table function” on page 333
– Updated services
- CANCEL_SQL allows a user to cancel their own job: “CANCEL_SQL procedure” on page 367
- CHANGE_DISK_PATHS selection includes an adapter option: “CHANGE_DISK_PATHS procedure”
on page 974
- CHANGE_USER_PROFILE allows special authorities to be changed: “CHANGE_USER_PROFILE
table function” on page 895
- DB_TRANSACTION_INFO lets users see their own transaction information:
“DB_TRANSACTION_INFO view” on page 457

Database performance and query optimization 3


- DISPLAY_JOURNAL has filters for commit cycle and internal entries: “DISPLAY_JOURNAL table
function” on page 784
- DUMP_PLAN_CACHE has filters for SQL statement text and system queries: “DUMP_PLAN_CACHE
procedure” on page 357
- LPRINTF can print a longer string: “LPRINTF procedure” on page 488
- NETSTAT_JOB_INFO returns the job name in individual columns: “NETSTAT_JOB_INFO view” on
page 568
- PARSE_STATEMENT table function returns additional details for DDL statements:
“PARSE_STATEMENT table function” on page 324
- PTF_INFO view returns the latest superseding PTF and has new authorization requirement:
“PTF_INFO view” on page 884
- REMOVE_TRACKED_JOB_QUEUE procedure can ignore errors when a job queue cannot be
accessed: “REMOVE_TRACKED_JOB_QUEUE procedure” on page 1090
- SYSTEM_STATUS_INFO view, SYSTEM_STATUS_INFO_BASIC view, and SYSTEM_STATUS table
function return both the machine serial number and the virtual serial number:
“SYSTEM_STATUS_INFO view” on page 1110, “SYSTEM_STATUS_INFO_BASIC view” on page 1118,
and “SYSTEM_STATUS table function” on page 1100
- SYSTEM_VALUE_INFO returns addition information about system values and a formatted version of
the system value: “SYSTEM_VALUE_INFO view” on page 1125
- USER_INFO_BASIC returns null for the USER_DEFAULT_PASSWORD column. Use the USER_INFO
view to access this information: “USER_INFO_BASIC view” on page 926
• May 2023 update
– New services
- AUDIT_JOURNAL_AP, AUDIT_JOURNAL_AX, AUDIT_JOURNAL_OR, AUDIT_JOURNAL_PA,
AUDIT_JOURNAL_PF, AUDIT_JOURNAL_PU, AUDIT_JOURNAL_RA, AUDIT_JOURNAL_RO, and
AUDIT_JOURNAL_RZ table functions return entry specific data: “AUDIT_JOURNAL_AP table
function” on page 674, “AUDIT_JOURNAL_AX table function” on page 676, “AUDIT_JOURNAL_OR
table function” on page 742, “AUDIT_JOURNAL_PA table function” on page 746,
“AUDIT_JOURNAL_PF table function” on page 748, “AUDIT_JOURNAL_PU table function” on page
759, “AUDIT_JOURNAL_RA table function” on page 762,“AUDIT_JOURNAL_RO table function” on
page 764, and “AUDIT_JOURNAL_RZ table function” on page 765
- DEFECTIVE_PTF_CURRENCY view identifies defective PTFs on the system without the
corresponding corrective PTF: “DEFECTIVE_PTF_CURRENCY view” on page 872
- DNS_LOOKUP_IP scalar function returns a hostname for a specified IP address: “DNS_LOOKUP_IP
scalar function” on page 552
- JVM_INFO table function provides a wait time option for accessing JVM information: “JVM_INFO
table function” on page 650
- NETWORK_ATTRIBUTE_INFO view returns information about the network attributes of the system:
“NETWORK_ATTRIBUTE_INFO view” on page 577
- RDB_ENTRY_INFO view returns information about RDB directory entries: “RDB_ENTRY_INFO view”
on page 588
- SAVE_FILE_INFO view returns information about save files: “SAVE_FILE_INFO view” on page 536
- SAVE_FILE_OBJECTS view and table function return information about objects within save files:
“SAVE_FILE_OBJECTS view” on page 541 and “SAVE_FILE_OBJECTS table function” on page 538
- SMAPP_ACCESS_PATHS view returns information about access paths monitored by System-
Managed Access Path Protection (SMAPP): “SMAPP_ACCESS_PATHS view” on page 825
- TAPE_CARTRIDGE_INFO view returns information about tape cartridges: “TAPE_CARTRIDGE_INFO
view” on page 542
– Updated services

4 IBM i: Performance and Query Optimization


- ASP_INFO view, SYSTEM_STATUS_INFO view, and SYSTEM_STATUS table function return SMAPP
information: “ASP_INFO view” on page 962, “SYSTEM_STATUS_INFO view” on page 1110 and
“SYSTEM_STATUS table function” on page 1100
- GROUP_PTF_INFO view has new authorization requirements: “GROUP_PTF_INFO view” on page
882
- JVM_INFO view returns the job name in individual columns: “JVM_INFO view” on page 652
- PROGRAM_INFO view returns copyright strings for ILE programs and service programs:
“PROGRAM_INFO view” on page 490
- PTF_INFO view returns additional product option information: “PTF_INFO view” on page 884
- STACK_INFO table function has a new IGNORE_ERRORS parameter to allow processing to continue
when an error is encountered: “STACK_INFO table function” on page 517
- SYSDISKSTAT view and table function return a hardware status value: “SYSDISKSTAT view” on
page 988 and “SYSDISKSTAT table function” on page 983
- SYSFILES view returns based on file information for logical files and views: “SYSFILES view” on
page 402
• December 2022 update
– SQL Error Logging Facility (SELF): “SQL Error Logging Facility (SELF)” on page 187, “SQL_ERROR_LOG
view” on page 331, “SELFCODES global variable” on page 331, “VALIDATE_SELF scalar function” on
page 334
– New services
- The PROCESS_SYSTEM_LIMITS_ALERTS procedure is documented:
“PROCESS_SYSTEM_LIMITS_ALERTS procedure” on page 1007
- AUDIT_JOURNAL_AD, AUDIT_JOURNAL_DS, AUDIT_JOURNAL_IM, AUDIT_JOURNAL_PG,
AUDIT_JOURNAL_SK, AUDIT_JOURNAL_SM, AUDIT_JOURNAL_ZC, and AUDIT_JOURNAL_ZR table
functions return entry specific data: “AUDIT_JOURNAL_AD table function” on page 662,
“AUDIT_JOURNAL_DS table function” on page 697, “AUDIT_JOURNAL_IM table function” on page
715, “AUDIT_JOURNAL_PG table function” on page 753, “AUDIT_JOURNAL_SK table function”
on page 766, “AUDIT_JOURNAL_SM table function” on page 768, “AUDIT_JOURNAL_ZC table
function” on page 780, and “AUDIT_JOURNAL_ZR table function” on page 782
- CHANGE_DISK_PATHS procedure: “CHANGE_DISK_PATHS procedure” on page 974
- COMMAND_INFO view returns information about CL commands: “COMMAND_INFO view” on page
436
- Hardware resource information: “HARDWARE_RESOURCE_INFO view” on page 609 and
“HARDWARE_RESOURCE_INFO table function” on page 602
- OBJECTCONNECT_INFO view and CHANGE_OBJECTCONNECT procedure provide ObjectConnect
over IP information: “OBJECTCONNECT_INFO view” on page 584 and “CHANGE_OBJECTCONNECT
procedure” on page 548
- Submitted Job Tracker services: “ADD_TRACKED_JOB_QUEUE procedure” on page 1026,
“CLEAR_TRACKED_JOB_INFO procedure” on page 1030, “REMOVE_TRACKED_JOB_QUEUE
procedure” on page 1090, “TRACKED_JOB_INFO table function” on page 1126, and
“TRACKED_JOB_QUEUES view” on page 1135
- Support for creating and managing locking policies for NVMe devices:
“ADD_DEVICE_LOCKING_POLICY procedure” on page 962, “CHANGE_DEVICE_LOCKING_POLICY
procedure” on page 974, “CREATE_LOCKING_POLICY procedure” on page 977,
“DELETE_LOCKING_POLICY procedure” on page 977, “FACTORY_RESET_DEVICE procedure” on
page 978, “LOCKING_POLICY_INFO view” on page 978, “REMOVE_DEVICE_LOCKING_POLICY
procedure” on page 983, and “UNLOCK_DEVICE procedure” on page 996
– Updated services
- ACTIVE_DB_CONNECTIONS table function returns information about Db2 Mirror suspend
processing: “ACTIVE_DB_CONNECTIONS table function” on page 544

Database performance and query optimization 5


- ACTIVE_JOB_INFO table function returns the workload group information with the WORK subset of
data: “ACTIVE_JOB_INFO table function” on page 1009
- ASP_INFO returns new geographic mirroring information: “ASP_INFO view” on page 962
- HISTORY_LOG_INFO returns the job name in individual columns: “HISTORY_LOG_INFO table
function” on page 842
- OUTPUT_QUEUE_ENTRIES view and table function return TOTAL_RECORDS, MAXIMUM_RECORDS,
and USER_DEFINED_DATA: “OUTPUT_QUEUE_ENTRIES view” on page 941 and
“OUTPUT_QUEUE_ENTRIES table function” on page 937
- OUTPUT_QUEUE_INFO returns the internet address: “OUTPUT_QUEUE_INFO view” on page 948
- SYSDISKSTAT returns world wide port number information for certain devices: “SYSDISKSTAT
view” on page 988 and “SYSDISKSTAT table function” on page 983
- SYSTEM_STATUS_INFO and SYSTEM_STATUS return basic summary information:
“SYSTEM_STATUS_INFO view” on page 1110 and “SYSTEM_STATUS table function” on page 1100
- WLM_SET_CLIENT_INFO procedure supports a verbose option: “WLM_SET_CLIENT_INFO
procedure” on page 335
• May 2022 update
– Query Supervisor example exit programs written in CL: “Query Supervisor example exit programs” on
page 216
– New services
- ACTIVATION_GROUP_INFO table function: “ACTIVATION_GROUP_INFO table function” on page
418
- ASSOCIATE_JOURNAL_RECEIVER table function: “ASSOCIATE_JOURNAL_RECEIVER table
function” on page 654
- AUDIT_JOURNAL_JS, AUDIT_JOURNAL_OM, and AUDIT_JOURNAL_ST table functions return entry
specific data: “AUDIT_JOURNAL_JS table function” on page 718, “AUDIT_JOURNAL_OM table
function” on page 740, and “AUDIT_JOURNAL_ST table function” on page 775
- BINDING_DIRECTORY_INFO view: “BINDING_DIRECTORY_INFO view” on page 421
- DNS_LOOKUP table function: “DNS_LOOKUP table function” on page 551
- ELECTRONIC_SERVICE_AGENT_INFO view: “ELECTRONIC_SERVICE_AGENT_INFO view” on page
873
- JOURNAL_RECEIVER_INFO view: “JOURNAL_RECEIVER_INFO view” on page 806
- MTI_INFO table function: “MTI_INFO table function” on page 349
- REMOTE_JOURNAL_INFO view: “REMOTE_JOURNAL_INFO view” on page 819
- SPOOLED_FILE_INFO table function: “SPOOLED_FILE_INFO table function” on page 957
- SQL_CHECK_FUNCTION_USAGE scalar function: “SQL_CHECK_FUNCTION_USAGE scalar function”
on page 916
- SQL_CHECK_SPECIAL_AUTHORITY scalar function: “SQL_CHECK_SPECIAL_AUTHORITY scalar
function” on page 916
- SYSTEM_ACTIVITY_INFO table function: “SYSTEM_ACTIVITY_INFO table function” on page 1099
- User space services: “CREATE_USER_SPACE procedure” on page 446, “CHANGE_USER_SPACE and
CHANGE_USER_SPACE_BINARY procedures” on page 432, “CHANGE_USER_SPACE_ATTRIBUTES
procedure” on page 433
- User index services: “CREATE_USER_INDEX procedure” on page 443,
“ADD_USER_INDEX_ENTRY and ADD_USER_INDEX_ENTRY_BINARY procedures” on page 420,
“REMOVE_USER_INDEX_ENTRY and REMOVE_USER_INDEX_ENTRY_BINARY table functions” on
page 508
– Updated services

6 IBM i: Performance and Query Optimization


- ACTIVE_JOB_INFO table function can return a WORK subset of data: “ACTIVE_JOB_INFO table
function” on page 1009
- GENERATE_PDF scalar function supports *LAST option: “GENERATE_PDF scalar function” on page
936
- GENERATE_SQL and GENERATE_SQL_OBJECTS procedures have a new option for generating
comments for tables: “GENERATE_SQL procedure” on page 378 and “GENERATE_SQL_OBJECTS
procedure” on page 387
- JOBLOG_INFO table function returns the qualified job name: “JOBLOG_INFO table function” on
page 847
- SYSTEM_STATUS table function, SYSTEM_STATUS_INFO view, and SYSTEM_STATUS_INFO_BASIC
view no longer return information for the AVERAGE_CPU_RATE, AVERAGE_CPU_UTILIZATION,
MINIMUM_CPU_UTILIZATION, and MAXIMUM_CPU_UTILIZATION columns due to performance
concerns. This information is now returned through the SYSTEM_ACTIVITY_INFO table function.
These columns can be can be explicitly requested by using an environment variable switch.
ADDENVVAR ENVVAR(QIBM_DB2_SYSTEM_STATUS_INFO) VALUE(FULL) LEVEL(*JOB)
“SYSTEM_STATUS table function” on page 1100, “SYSTEM_STATUS_INFO view” on page 1110, and
“SYSTEM_STATUS_INFO_BASIC view” on page 1118
• September 2021 update
– New system limits global variables provide the ability to remove rows from the system limits table by
the age of rows, in days: “QIBM_SYSTEM_LIMITS global variables” on page 1008
– New services
- ACTIVE_QUERY_INFO table function returns information about active SQL Query Engine (SQE)
queries: “ACTIVE_QUERY_INFO table function” on page 338
- AUDIT_JOURNAL_CD, AUDIT_JOURNAL_CO, AUDIT_JOURNAL_CP, AUDIT_JOURNAL_DO,
AUDIT_JOURNAL_EV, AUDIT_JOURNAL_GR, AUDIT_JOURNAL_M0, AUDIT_JOURNAL_M6,
AUDIT_JOURNAL_M7, AUDIT_JOURNAL_M8, AUDIT_JOURNAL_M9, AUDIT_JOURNAL_SV table
functions return the entry specific data for audit journal entries: “Audit journal entry services”
on page 658
- COLLECTION_SERVICES_INFO returns the configuration properties for Collection Services:
“COLLECTION_SERVICES_INFO view” on page 859
- SYSFILES view returns database file information: “SYSFILES view” on page 402
- WORKLOAD_GROUP_INFO view returns information about workload groups:
“WORKLOAD_GROUP_INFO view” on page 1136
– Updated services
- ACTIVE_JOB_INFO includes a column for the workload group: “ACTIVE_JOB_INFO table function”
on page 1009
- DISPLAY_JOURNAL table function adds a column with a new name to return the current user value:
“DISPLAY_JOURNAL table function” on page 784
- NVME_INFO view provides more information about NVMe devices: “NVME_INFO view” on page
979
- PARSE_STATEMENT returns the procedure name for a CALL statement: “PARSE_STATEMENT table
function” on page 324
- SECURITY_INFO view returns additional security-related system values: “SECURITY_INFO view”
on page 910
- SYSDISKSTAT view and SYSDISKSTAT table function return additional information about NVMe
devices: “SYSDISKSTAT view” on page 988 and “SYSDISKSTAT table function” on page 983
• April 2021 update

Database performance and query optimization 7


– The Query Supervisor allows real time monitoring of resources used by queries: “Query Supervisor”
on page 211
– New services
- AUDIT_JOURNAL_AF, AUDIT_JOURNAL_CA, AUDIT_JOURNAL_OW, AUDIT_JOURNAL_PW table
functions return the entry specific data for audit journal entries: “Audit journal entry services”
on page 658
- CHANGE_USER_PROFILE table function allows some user profile attributes to be changed:
“CHANGE_USER_PROFILE table function” on page 895
- END_IDLE_SQE_THREADS procedure ends SQE threads not being used by a job:
“END_IDLE_SQE_THREADS procedure ” on page 374
- GENERATE_PDF scalar function generates a PDF from a spooled file: “GENERATE_PDF scalar
function” on page 936
- MESSAGE_QUEUE_INFO table function allows filtering of the messages in a message queue:
“MESSAGE_QUEUE_INFO table function” on page 852
- NVME_INFO view provides information about NVMe devices: “NVME_INFO view” on page 979
- QCMDEXC scalar function executes a CL command from within a query: “QCMDEXC scalar function”
on page 505
- SECURITY_INFO view provides system security settings: “SECURITY_INFO view” on page 910
- SEND_MESSAGE procedure sends an informational message to the QSYSOPR message queue:
“SEND_MESSAGE procedure ” on page 858
- USER_INDEX_INFO view returns the attributes of a *USRIDX: “USER_INDEX_INFO view” on page
523
- USER_INDEX_ENTRIES table function returns the contents of a *USRIDX: “USER_INDEX_ENTRIES
table function” on page 522
- USER_INFO_BASIC view is a faster version of USER_INFO, with fewer columns:
“USER_INFO_BASIC view” on page 926
- USER_SPACE_INFO view returns the attributes of a *USRSPC: “USER_SPACE_INFO view” on page
525
- USER_SPACE table function returns the content of a *USRSPC object: “USER_SPACE table function”
on page 524
– Updated services
- ACTIVE_JOB_INFO and JOB_INFO table functions return individual columns for the parts of
a qualified job name: “ACTIVE_JOB_INFO table function” on page 1009 and “JOB_INFO table
function” on page 1046
- CLEAR_PLAN_CACHE procedure allows a plan for a query to be cleared: “CLEAR_PLAN_CACHE
procedure ” on page 356
- DISPLAY_JOURNAL table function returns more SYSLOG information: “DISPLAY_JOURNAL table
function” on page 784
- DUMP_PLAN_CACHE procedure allows a specific plan to be dumped: “DUMP_PLAN_CACHE
procedure” on page 357
- DUMP_PLAN_CACHE_TOPN procedure supports additional categories of plans to be dumped:
“DUMP_PLAN_CACHE_TOPN procedure” on page 360
- FIRMWARE_CURRENCY view includes information shown by the DSPFMWSTS command:
“FIRMWARE_CURRENCY view” on page 874
- GENERATE_SQL and GENERATE_SQL_OBJECTS procedures write output to a stream file:
“GENERATE_SQL procedure” on page 378 and “GENERATE_SQL_OBJECTS procedure” on page 387
- IFS_OBJECT_STATISTICS table function return the symbolic link for an object:
“IFS_OBJECT_STATISTICS table function” on page 629

8 IBM i: Performance and Query Optimization


- OBJECT_STATISTICS table function supports a generic object name: “OBJECT_STATISTICS table
function” on page 834
- SYSDISKSTAT view and SYSDISKSTAT table function return additional information about SSDs,
including remaining lifetime: “SYSDISKSTAT view” on page 988 and “SYSDISKSTAT table function”
on page 983
- USER_INFO view indicates whether the user profile is disabled for IBM i NetServer use:
“USER_INFO view” on page 917
– System limit alerting is instrumented for the maximum number of spooled files limit. In addition,
global variables can be used to set the alerting level percent for each limit: “System limit alerts” on
page 1000
• October 2020 update
– The SELECTIVITY clause allows predicate selectivity values to be assigned within a query: “Use
SELECTIVITY to supply missing information” on page 313
– New services
- COMMUNICATIONS_ENTRY_INFO view: “COMMUNICATIONS_ENTRY_INFO view” on page 1032
- DATA_QUEUE_ENTRIES table function: “DATA_QUEUE_ENTRIES table function” on page 452
- EXIT_POINT_INFO view: “EXIT_POINT_INFO view” on page 482
- EXIT_PROGRAM_INFO view: “EXIT_PROGRAM_INFO view” on page 484
- IFS_READ table function: “IFS_READ, IFS_READ_BINARY, and IFS_READ_UTF8 table functions” on
page 641
- IFS_WRITE procedure: “IFS_WRITE, IFS_WRITE_BINARY, and IFS_WRITE_UTF8 procedures” on
page 645
- JOURNAL_INHERIT_RULES view: “JOURNAL_INHERIT_RULES view” on page 826
- JOURNALED_OBJECTS view: “JOURNALED_OBJECTS view” on page 815
- OPEN_FILES table function: “OPEN_FILES table function” on page 1081
- RELATED_OBJECTS table function: “RELATED_OBJECTS table function” on page 398
- SERVER_SHARE_INFO view: “SERVER_SHARE_INFO view” on page 647
- SOFTWARE_PRODUCT_INFO view: “SOFTWARE_PRODUCT_INFO view” on page 867
- SYSLIMITS_BASIC view: “SYSLIMITS_BASIC view” on page 1006
- WATCH_DETAIL table function: “WATCH_DETAIL table function” on page 526
- WATCH_INFO view: “WATCH_INFO view” on page 531
– Updated services
- ACTIVE_JOB_INFO table function returns a column about open files: “ACTIVE_JOB_INFO table
function” on page 1009
- ANALYZE_CATALOG table function has an option to return cross reference server status:
“ANALYZE_CATALOG table function” on page 365
- DB_TRANSACTION_INFO view returns additional columns for pending changes:
“DB_TRANSACTION_INFO view” on page 457
- DISPLAY_JOURNAL table function allows multiple object names and a fully qualified job name as
input parameters, and returns more SYSLOG information: “DISPLAY_JOURNAL table function” on
page 784
- GROUP_PTF_DETAILS and GROUP_PTF_CURRENCY views return dates as a date data type column:
“GROUP_PTF_DETAILS view” on page 878 and “GROUP_PTF_CURRENCY view” on page 877
- LIBRARY_INFO table function has a new detailed information parameter and returns additional
journal columns: “LIBRARY_INFO table function” on page 830
- SPLIT table function has an escape character parameter: “SPLIT table function” on page 516

Database performance and query optimization 9


- SYSDISKSTAT view has additional information added, including statistics. The new SYSDISKSTAT
table function allows the statistics to be reset: “SYSDISKSTAT view” on page 988 and
“SYSDISKSTAT table function” on page 983
- SYSTEM_STATUS table function and SYSTEM_STATUS_INFO view return job table information and
system-wide journal information. A new view, SYSTEM_STATUS_INFO_BASIC does not return the
job table columns: “SYSTEM_STATUS table function” on page 1100, “SYSTEM_STATUS_INFO view”
on page 1110, and “SYSTEM_STATUS_INFO_BASIC view” on page 1118
– SYSTOOLS services are documented
- DELETE_OLD_SPOOLED_FILES procedure: “DELETE_OLD_SPOOLED_FILES procedure” on page 934
- LPRINTF procedure: “LPRINTF procedure” on page 488
- VALIDATE_DATA table functions: “VALIDATE_DATA, VALIDATE_DATA_FILE, and
VALIDATE_DATA_LIBRARY table functions” on page 416
• April 2020 update
– New services
- ANALYZE_CATALOG table function: “ANALYZE_CATALOG table function” on page 365
- AUTOSTART_JOB_INFO view: “AUTOSTART_JOB_INFO view” on page 1029
- CERTIFICATE_INFO table function: “CERTIFICATE_INFO table function” on page 892
- COMPARE_FILE table function: “COMPARE_FILE table function” on page 371
- DB_TRANSACTION_INFO table function: “DB_TRANSACTION_INFO view” on page 457
- HTTP_SERVER_INFO view: “HTTP_SERVER_INFO view” on page 553
- IFS_OBJECT_STATISTICS table function: “IFS_OBJECT_STATISTICS table function” on page 629
- JOB_LOCK_INFO table function: “JOB_LOCK_INFO table function” on page 1058
- LIBRARY_INFO table function: “LIBRARY_INFO table function” on page 830
- PRESTART_JOB_INFO view: “PRESTART_JOB_INFO view” on page 1083
- PRESTART_JOB_STATISTICS table function: “PRESTART_JOB_STATISTICS table function” on page
1086
- ROUTING_ENTRY_INFO view: “ROUTING_ENTRY_INFO view” on page 1091
- SUBSYSTEM_INFO view: “SUBSYSTEM_INFO view” on page 1096
- SUBSYSTEM_POOL_INFO view: “SUBSYSTEM_POOL_INFO view” on page 1098
- WORKSTATION_INFO view: “WORKSTATION_INFO view” on page 1137
– Updated services
- ACTIVE_JOB_INFO table function returns enhanced job type: “ACTIVE_JOB_INFO table function”
on page 1009
- DISPLAY_JOURNAL table function returns more SYSLOG information: “DISPLAY_JOURNAL table
function” on page 784
- OBJECT_PRIVILEGES table function has been documented: “OBJECT_PRIVILEGES table function”
on page 904
- OBJECT_PRIVILEGES view has 2 new columns: “OBJECT_PRIVILEGES view” on page 907
- OVERRIDE_QAQQINI procedure allows optional parameters: “OVERRIDE_QAQQINI procedure” on
page 322
- SYSDISKSTAT returns information for NVMe storage: “SYSDISKSTAT view” on page 988
- SYSTEM_STATUS table function and SYSTEM_STATUS_INFO view return additional columns:
“SYSTEM_STATUS table function” on page 1100 and “SYSTEM_STATUS_INFO view” on page 1110
- USER_INFO view has new columns: “USER_INFO view” on page 917
• October 2019 update
– New option to suppress alter table inquiry message. “QAQQINI query options” on page 196

10 IBM i: Performance and Query Optimization


– New services
- ACTIVE_DB_CONNECTIONS table function: “ACTIVE_DB_CONNECTIONS table function” on page
544
- DATA_QUEUE_INFO view: “DATA_QUEUE_INFO view” on page 454
- SEND_DATA_QUEUE procedure: “SEND_DATA_QUEUE, SEND_DATA_QUEUE_BINARY, and
SEND_DATA_QUEUE_UTF8 procedures” on page 510
- RECEIVE_DATA_QUEUE table function: “RECEIVE_DATA_QUEUE table function” on page 505
- CLEAR_DATA_QUEUE procedure: “CLEAR_DATA_QUEUE procedure” on page 434
- BOUND_MODULE_INFO view: “BOUND_MODULE_INFO view” on page 422
- BOUND_SRVPGM_INFO view: “BOUND_SRVPGM_INFO view” on page 431
- PROGRAM_EXPORT_IMPORT_INFO view: “PROGRAM_EXPORT_IMPORT_INFO view” on page 488
- PROGRAM_INFO view: “PROGRAM_INFO view” on page 490
- IFS_JOB_INFO table function: “IFS_JOB_INFO table function” on page 617
- IFS_OBJECT_LOCK_INFO table function: “IFS_OBJECT_LOCK_INFO table function” on page 621
- IFS_OBJECT_REFERENCES_INFO table function: “IFS_OBJECT_REFERENCES_INFO table function”
on page 626
- IFS_OBJECT_STATISTICS table function: “IFS_OBJECT_STATISTICS table function” on page 629
- OBJECT_OWNERSHIP view: “OBJECT_OWNERSHIP view” on page 901
- SERVER_SBS_CONFIGURATION view: “SERVER_SBS_CONFIGURATION view” on page 591
- SWAP_DYNUSRPRF procedure: “SWAP_DYNUSRPRF procedure” on page 401
– Updated services
- JOBLOG_INFO table function has optional error handling parameter: “JOBLOG_INFO table
function” on page 847
- OBJECT_PRIVILEGES view: “OBJECT_PRIVILEGES view” on page 907
- OBJECT_STATISTICS table function returns additional columns: “OBJECT_STATISTICS table
function” on page 834
- Support for server routing by IP address added to SET_SERVER_SBS_ROUTING:
“SET_SERVER_SBS_ROUTING procedure” on page 595
- SYSTEM_STATUS table function and SYSTEM_STATUS_INFO view return additional columns:
“SYSTEM_STATUS table function” on page 1100 and “SYSTEM_STATUS_INFO view” on page 1110

What's new since the first 7.3 publication


The following revisions or additions were made to the Performance and query optimization
documentation after the first 7.3 publication:
• STATEMENT DETERMINISTIC option has been added for functions: “QAQQINI query options” on page
196
• New services
– ASP_INFO view: “ASP_INFO view” on page 962
– ASP_VARY_INFO view: “ASP_VARY_INFO view” on page 972
– AUTHORIZATION_LIST_INFO view: “AUTHORIZATION_LIST_INFO view” on page 888
– AUTHORIZATION_LIST_USER_INFO view: “AUTHORIZATION_LIST_USER_INFO view” on page 890
– GENERATE_SQL_OBJECTS procedure: “GENERATE_SQL_OBJECTS procedure” on page 387
– HISTORY_LOG_INFO table function: “HISTORY_LOG_INFO table function” on page 842
– JOB_DESCRIPTION_INFO view: “JOB_DESCRIPTION_INFO view” on page 1039
– JOB_INFO table function: “JOB_INFO table function” on page 1046

Database performance and query optimization 11


– JOB_QUEUE_INFO view: “JOB_QUEUE_INFO view” on page 1071
– LICENSE_EXPIRATION_CHECK procedure: “LICENSE_EXPIRATION_CHECK procedure” on page 864
– MESSAGE_QUEUE_INFO view: “MESSAGE_QUEUE_INFO view” on page 855
– OBJECT_PRIVILEGES view: “OBJECT_PRIVILEGES view” on page 907
– OUTPUT_QUEUE_ENTRIES_BASIC view: “OUTPUT_QUEUE_ENTRIES_BASIC view” on page 946
– PARSE_STATEMENT table function: “PARSE_STATEMENT table function” on page 324
– SET_PASE_SHELL_INFO procedure: “SET_PASE_SHELL_INFO procedure” on page 515
– STACK_INFO table function: “STACK_INFO table function” on page 517
• Updated services
– ACTIVE_JOB_INFO table function optionally returns more detailed information: “ACTIVE_JOB_INFO
table function” on page 1009
– DISPLAY_JOURNAL includes syslog information and honors row and column access control:
“DISPLAY_JOURNAL table function” on page 784,
– GET_JOB_INFO table function has new columns for prestart job information: “GET_JOB_INFO table
function” on page 1037
– GROUP_PTF_CURRENCY view returns a new value to indicate PTFs will be current with the next IPL:
“GROUP_PTF_CURRENCY view” on page 877
– LICENSE_INFO view has a new column indicating the install status: “LICENSE_INFO view” on page
865
– NETSTAT_INFO view and NETSTAT_JOB_INFO view return port names from service table entries:
“NETSTAT_INFO view” on page 554 and “NETSTAT_JOB_INFO view” on page 568
– OBJECT_STATISTICS table function added an option to efficiently return a list of libraries:
“OBJECT_STATISTICS table function” on page 834
– OVERRIDE_QAQQINI procedure has been fully documented: “OVERRIDE_QAQQINI procedure” on
page 322
– RESET_TABLE_INDEX_STATISTICS procedure has a new option to remove rows from the index advice
tracking table: “RESET_TABLE_INDEX_STATISTICS procedure” on page 353
– System limit notifications: “System limit alerts” on page 1000
– USER_INFO has new columns for supplemental group profile information and the PASE shell:
“USER_INFO view” on page 917

How to see what's new or changed


To help you see where technical changes have been made, this information uses:
• The image to mark where new or changed information begins.
• The image to mark where new or changed information ends.
To find other information about what's new or changed this release, see the Memo to users.

PDF file for Database performance and query optimization


View and print a PDF of this information.
To view or download the PDF version of this document, select Database performance and query
optimization.

Other information
You can also view or print any of the following PDF files:

• Preparing for and Tuning the SQL Query Engine on DB2® for i5/OS

12 IBM i: Performance and Query Optimization


• SQL Performance Diagnosis on IBM DB2 Universal Database for iSeries
.

Saving PDF files


To save a PDF on your workstation for viewing or printing:
1. Right-click the PDF in your browser (right-click the preceding link).
2. Click the option that saves the PDF locally.
3. Navigate to the directory in which you want to save the PDF.
4. Click Save.

Downloading Adobe Reader


You need Adobe Reader installed on your system to view or print these PDF files. You can download a free
copy from Adobe (http://get.adobe.com/reader/) .

Query engine overview


IBM Db2 for i provides two query engines to process queries: Classic Query Engine (CQE) and SQL Query
Engine (SQE).
SQL-based interfaces, such as ODBC, JDBC, CLI, Query Manager, Net.Data®®, RUNSQLSTM, and
embedded or interactive SQL, run through SQE. Also some non-SQL based interface such as OPNQRYF
and Query/400® will run through SQE. The CQE processes queries originating from non-SQL interfaces:
QQQQry API. For ease of use, the routing decision for processing the query by either CQE or SQE is
pervasive and under the control of the system. The requesting user or application program cannot control
or influence this behavior. However, a better understanding of the engines and process that determines
which path a query takes can give you a better understanding of query performance.
Within SQE, several more components were created and other existing components were updated.
Additionally, new data access methods are possible with SQE that are not supported under CQE.
Related information
Embedded SQL programming
SQL programming
Query (QQQQRY) API
Open Query File (OPNQRYF) command
Run SQL Statements (RUNSQLSTM) command

SQE and CQE engines


It is important to understand the implementation differences of query management and processing in
CQE versus SQE.
The following figure shows an overview of the IBM Db2 for i architecture. It shows the delineation
between CQE and SQE, how query processing is directed by the query dispatcher, and where each SQE
component fits. The functional separation of each SQE component is clearly evident. This division of
responsibility enables IBM to more easily deliver functional enhancements to the individual components
of SQE, as and when required. Notice that most of the SQE Optimizer components are implemented below
the MI. This implementation translates into enhanced performance efficiency.

Database performance and query optimization 13


As seen in the previous graphic, the query runs from any query interface to the optimizer and the query
dispatcher. The query dispatcher determines whether the query is implemented with CQE or SQE.

Query dispatcher
The function of the dispatcher is to route the query request to either CQE or SQE, depending on the
attributes of the query. All queries are processed by the dispatcher. It cannot be bypassed.
Currently, the dispatcher routes queries to SQE unless it finds that the query references or contains any of
the following:
• INSERT WITH VALUES statement or the target of an INSERT with subselect statement
• Tables with Read triggers
• Read-only queries with more than 1000 dataspaces, or updatable queries with more than 256
dataspaces.
• Db2 Multisystem tables
• QQQQry API
In earlier releases, for other non-SQL queries, for example Query/400 or OPNQRYF, the routing of the
query could be controlled by the QAQQINI SQE_NATIVE_ACCESS option. SQE_NATIVE_ACCESS is no
longer supported and a non-SQL query will always run SQE unless unless it contains one of the conditions
listed above.

14 IBM i: Performance and Query Optimization


Related reference
MQT supported function
Although an MQT can contain almost any query, the optimizer only supports a limited set of query
functions when matching MQTs to user specified queries. The user-specified query and the MQT query
must both be supported by the SQE optimizer.

Statistics manager
In CQE, the retrieval of statistics is a function of the Optimizer. When the Optimizer needs to know
information about a table, it looks at the table description to retrieve the row count and table size.
If an index is available, the Optimizer might extract information about the data in the table. In SQE,
the collection and management of statistics is handled by a separate component called the statistics
manager. The statistics manager leverages all the same statistical sources as CQE, but adds more sources
and capabilities.
The statistics manager does not actually run or optimize the query. Instead, it controls the access to the
metadata and other information that is required to optimize the query. It uses this information to answer
questions posed by the query optimizer. The statistics manager always provides answers to the optimizer.
In cases where it cannot provide an answer based on actual existing statistics information, it is designed
to provide a predefined answer.
The Statistics manager typically gathers and tracks the following information:

Cardinality of The number of unique or distinct occurrences of a specific value in a single column
values or multiple columns of a table.
Selectivity Also known as a histogram, this information is an indication of how many rows
are selected by any given selection predicate or combination of predicates. Using
sampling techniques, it describes the selectivity and distribution of values in a given
column of the table.
Frequent values The top nn most frequent values of a column together with a count of how
frequently each value occurs. This information is obtained by using statistical
sampling techniques. Built-in algorithms eliminate the possibility of data skewing.
For example, NULL values and default values that can influence the statistical values
are not taken into account.
Metadata Includes the total number of rows in the table, indexes that exist over the table, and
information which indexes are useful for implementing the particular query.
Estimate of IO An estimate of the amount of IO operations that are required to process the table or
operation the identified index.

The Statistics manager uses a hybrid approach to manage database statistics. Most of this information
can be obtained from existing indexes. In cases where the required statistics cannot be gathered from
existing indexes, statistical information is constructed on single columns of a table and stored internally.
By default, this information is collected automatically by the system, but you can manually control the
collection of statistics. Unlike indexes, however, statistics are not maintained immediately as data in the
tables change.
Related reference
Collecting statistics with the statistics manager
The collection of statistics is handled by a separate component called the statistics manager. Statistical
information can be used by the query optimizer to determine the best access plan for a query. Since

Database performance and query optimization 15


the query optimizer bases its choice of access plan on the statistical information found in the table, it is
important that this information is current.

Global Statistics Cache


In SQE, the Db2 Statistics Manager stores actual row counts into a Global Statistics Cache. In this manner,
the Statistics Manager refines its estimates over time as it learns where estimates have deviated from
actual row counts.
Both completed queries and currently executing queries might be inspected by the “Adaptive Query
Processing” on page 109 (AQP) task, which compares estimated row counts to actual row counts. If there
are any significant discrepancies, the AQP task notifies the Db2 Statistics Manager (SM). The SM stores
this actual row count (also called observed row count) into a Global Statistics Cache (GSC).
If the query which generated the observed statistic in the GSC is reoptimized, the actual row count
estimate is used in determining a new query plan. Further, if a different query asks for the same or a
similar row count, the SM could return the stored actual row count from the GSC. Faster query plans can
be generated by the query optimizer.
Typically, observed statistics are for complex predicates such as with a join. A simple example is a query
joining three files A, B, and C. There is a discrepancy between the estimate and actual row count of the
join of A and B. The SM stores an observed statistic into the GSC. Later, if a different join query of A, B, and
Z is submitted, the SM recalls the observed statistic of the A and B join. The SM considers that observed
statistic in its estimate of the A, B, and Z join.
The Global Statistics Cache is an internal Db2 object, and the contents of it are not directly observable.

Plan cache
The plan cache is a repository that contains the access plans for queries that were optimized by SQE.
Access plans generated by CQE are not stored in the plan cache; instead, they are stored in SQL packages,
the system-wide statement cache, and job cache. The purposes of the plan cache are to:
• Facilitate the reuse of a query access plan when the same query is re-executed
• Store runtime information for subsequent use in future query optimizations
• Provide performance information for analysis and tuning
Once an access plan is created, it is available for use by all users and all queries, regardless of where
the query originates. Furthermore, when an access plan is tuned, for example, when creating an index,
all queries can benefit from this updated access plan. This updated access plan eliminates the need to
re-optimize the query, resulting in greater efficiency.
The following graphic shows the concept of re-usability of the query access plans stored in the plan
cache:

16 IBM i: Performance and Query Optimization


As shown in the previous graphic, statements from packages and programs are stored in unique plans in
the plan cache. If Statement 3 exists in both SQL package 1 and SQL package 2, the plan is stored once in
the plan cache. The plan cache is interrogated each time a query is executed. If an access plan exists that
satisfies the requirements of the query, it is used to implement the query. Otherwise a new access plan is
created and stored in the plan cache for future use.
The plan cache is automatically updated with new query access plans as they are created. When new
statistics or indexes become available, an existing plan is updated the next time the query is run. The plan
cache is also automatically updated by the database with runtime information as the queries are run.
Each plan cache entry contains the original query, the optimized query access plan, and cumulative
runtime information gathered during the runs of the query. The size of these objects depends largely
on the complexity of the SQL statements that are being executed. It is the size of these objects that is
counted when calculating the plan cache size.
The size of the plan cache may be controlled by either a system-managed auto-sizing algorithm or by an
explicitly set value. By default, the system will use automatic sizing, but this can be disabled by setting
the SQL Plan Cache Threshold Size. See the SQL plan cache properties topic for more information: “SQL
plan cache properties” on page 175
When auto-sizing is enabled, the system will begin after each IPL with a default plan cache size of 512
MB. As queries run, the associated plans are placed into the plan cache. Once the plan cache exceeds
the current limit set by auto-sizing, the system will evaluate the current hit ratio for the cache. This is the
ratio of the number of times a query could re-use a plan from the cache compared to the number of times
a query was run. For example, if ten queries were run and nine of the queries used plans from the plan
cache while the other one required a full optimization, the hit ratio is 90%. If the current hit ratio equals or
exceeds the SQL Plan Cache Target Ratio ( see the SQL plan cache properties topic for more information:
“SQL plan cache properties” on page 175), the system considers the plan cache to be operating at an
efficient size and will not adjust the size of the cache.
If the current hit ratio is below the target for the plan cache and no other storage constraints exist, the
system will automatically increase (up to the Maximum Plan Cache Size for Auto-sizing) the size of the

Database performance and query optimization 17


plan cache. The plan cache will grow incrementally, allowing more plans to be stored, until the current hit
ratio meets the target ratio.
Once the target hit ratio has been achieved, the determined size of the cache is maintained by an
automatically scheduled background task. The purpose of this task is to go through the plan cache and to
remove plans when the cache grows too large. This task will remove access plans based upon age, how
frequently it is used, and how much cumulative resources (CPU/IO) were consumed.
Each plan cache entry may also have query runtime objects associated with it. These runtime objects
are the real executable objects and temporary storage containers (hash tables, sorts, temporary indexes,
and so on) used to run the query. Although these objects are not included the in the plan cache size
calculation, they may indirectly affect and be affected by the plan cache size. This is because, in addition
to honoring the determined plan cache size, the system also seeks to keep the total temporary storage
usage for inactive, cached plans within an internally determined threshold. Unlike the plan cache size
calculation, this temporary storage calculation considers both the cached plans and the associated
runtime objects. If this temporary storage calculation exceeds a system determined percentage of the
system auxiliary storage pool (ASP) or if the system storage lower limit (defined by QSTGLOWLMT) is
surpassed, the system considers the plan cache to be using excessive temporary storage.
To reduce the excessive temporary storage, the automatically scheduled background task will begin
by removing runtime objects from cached plans. This will continue until the plan cache’s temporary
storage usage is within the system’s constraints, and this will happen even if all the cached plan entries
themselves fit within the determined plan cache size. If temporary storage usage remains excessive even
after the runtime objects are removed, the system will begin a process of incrementally reducing the plan
cache size and will continue this reduction until it reaches the minimum value of 512 MB or until the plan
cache temporary storage usage is no longer excessive.
Predicting the interaction between plan cache auto-sizing and the temporary storage constraint can be
difficult to do. In general, though, these recommendations should be followed:
• Use automatic plan cache sizing unless there is a clear reason to do otherwise.
• Determine and set an acceptable target hit ratio.
• Use an adequately sized system *ASP so that the system has plenty of temporary storage space
available.
Multiple access plans for a single SQL statement can be maintained in the plan cache. Although the SQL
statement is the primary key into the plan cache, different environmental settings can cause additional
access plans to be stored. Examples of these environmental settings include:
• Different SMP Degree settings for the same query
• Different library lists specified for the query tables
• Different settings for the share of available memory for the job in the current pool
• Different ALWCPYDTA settings
• Different selectivity based on changing host variable values used in selection (WHERE clause)
Currently, the plan cache can maintain a maximum of three different access plans for the same SQL
statement. As new access plans are created for the same SQL statement, older access plans are
discarded to make room for the new access plans. There are, however, certain conditions that can cause
an existing access plan to be invalidated. Examples of these conditions include:
• Specifying REOPTIMIZE_ACCESS_PLAN(*YES) or (*FORCE) in the QAQQINI table or in Run SQL Scripts
• Deleting or recreating the table that the access plan refers to
• Deleting an index that is used by the access plan
Related reference
Effects of the ALWCPYDTA parameter on database performance
Some complex queries can perform better by using a sort or hashing method to evaluate the query
instead of using or creating an index.
Changing the attributes of your queries

18 IBM i: Performance and Query Optimization


You can modify different types of query attributes for a job with the Change Query Attributes
(CHGQRYA) CL command. You can also use the System i Navigator Change Query Attributes interface.
Optimizing performance using the Plan Cache
The SQL Plan Cache contains a wealth of information about the SQE queries being run through the
database. Its contents are viewable through the System i Navigator GUI interface. Certain portions of the
plan cache can also be modified.

Data access methods


Data access methods are used to process queries and access data.
In general, the query engine has two kinds of raw material with which to satisfy a query request:
• The database objects that contain the data to be queried
• The executable instructions or operations to retrieve and transform the data into usable information
There are only two types of permanent database objects that can be used as source material for a query
— tables and indexes. Indexes include binary radix and encoded vector indexes.
In addition, the query engine might need to create temporary objects to hold interim results or
references during the execution of an access plan. The Db2 Symmetric Multiprocessing feature provides
the optimizer with additional methods for retrieving data that include parallel processing. Finally, the
optimizer uses certain methods to manipulate these objects.

Permanent objects and access methods


There are three basic types of access methods used to manipulate the permanent and temporary
database objects -- Create, Scan, and Probe.
The following table lists each object and the access methods that can be performed against that object.
The symbols shown in the table are the icons used by Visual Explain.

Table 1. Permanent object data access methods


Permanent objects Scan operations Probe operations
Table Table scan Table probe
Radix index Radix index scan Radix index probe
Encoded vector index Encoded vector index symbol Encoded vector index probe
table scan

Table
An SQL table or physical file is the base object for a query. It represents the source of the data used
to produce the result set for the query. It is created by the user and specified in the FROM clause (or
OPNQRYF FILE parameter).
The optimizer determines the most efficient way to extract the data from the table in order to satisfy the
query. These ways could include scanning or probing the table or using an index to extract the data.
Visual explain icon:

Database performance and query optimization 19


Table scan
A table scan is the easiest and simplest operation that can be performed against a table. It sequentially
processes all the rows in the table to determine if they satisfy the selection criteria specified in the query.
It does this processing in a way to maximize the I/O throughput for the table.
A table scan operation requests large I/Os to bring as many rows as possible into main memory for
processing. It also asynchronously pre-fetches the data to make sure that the table scan operation is
never waiting for rows to be paged into memory. Table scan however, has a disadvantage in it has to
process all the rows in order to satisfy the query. The scan operation itself is efficient if it does not need to
perform the I/O synchronously.

Table 2. Table scan attributes


Data access method Table scan
Description Reads all the rows from the table and applies the selection criteria to
each of the rows within the table. The rows in the table are processed
in no guaranteed order, but typically they are processed sequentially.
Advantages • Minimizes page I/O operations through asynchronous pre-fetching of
the rows since the pages are scanned sequentially
• Requests a larger I/O to fetch the data efficiently

Considerations • All rows in the table are examined regardless of the selectivity of the
query
• Rows marked as deleted are still paged into memory even though
none are selected. You can reorganize the table to remove deleted
rows.

Likely to be used • When expecting many rows returned from the table
• When the number of large I/Os needed to scan is fewer than the
number of small I/Os required to probe the table

Example SQL statement


SELECT * FROM Employee
WHERE WorkDept BETWEEN 'A01'AND 'E01'
OPTIMIZE FOR ALL ROWS

Database Monitor and Plan QQRID 3000 - Table Scan


Cache record indicating use
SMP parallel enabled Yes
Also referred to as Table Scan, Preload
Visual Explain icon

Related concepts
Nested loop join implementation

20 IBM i: Performance and Query Optimization


Db2 for i provides a nested loop join method. For this method, the processing of the tables in the join
are ordered. This order is called the join order. The first table in the final join order is called the primary
table. The other tables are called secondary tables. Each join table position is called a dial.

Table probe
A table probe operation is used to retrieve a specific row from a table based upon its row number. The
row number is provided to the table probe access method by some other operation that generates a row
number for the table.
This can include index operations as well as temporary row number lists or bitmaps. The processing for a
table probe is typically random. It requests a small I/O to retrieve only the row in question and does not
attempt to bring in any extraneous rows. This method leads to efficient processing for smaller result sets
because only rows needed to satisfy the query are processed, rather than scanning all rows.
However, since the sequence of the row numbers is not known in advance, little pre-fetching can be
performed to bring the data into main memory. This randomness can result in most of the I/Os associated
with table probe to be performed synchronously.

Table 3. Table probe attributes


Data access method Table probe
Description Reads a single row from the table based upon a specific row number. A
random I/O is performed against the table to extract the row.
Advantages • Requests smaller I/Os to prevent paging rows into memory that are
not needed
• Can be used with any access method that generates a row number
for the table probe to process

Considerations Because of the synchronous random I/O the probe can perform poorly
when many rows are selected
Likely to be used • When row numbers (from indexes or temporary row number lists)
are used, but data from the underlying table is required for further
processing of the query
• When processing any remaining selection or projection of the values

Example SQL statement


CREATE INDEX X1 ON Employee (LastName)

SELECT * FROM Employee


WHERE WorkDept BETWEEN 'A01' AND 'E01'
AND LastName IN ('Smith', 'Jones', 'Peterson')
OPTIMIZE FOR ALL ROWS

Database Monitor and Plan QQRID 3001 Index Used, where QVC14 (Index_Only_Access) set to 'N'
Cache record indicating use indicates that a table probe was used in conjunction with the index
access operation.

SMP parallel enabled Yes


Also referred to as Table Probe, Preload
Visual Explain icon

Database performance and query optimization 21


Radix index
An SQL index (or keyed sequence access path) is a permanent object that is created over a table. The
index is used by the optimizer to provide a sequenced view of the data for a scan or probe operation.
The rows in the tables are sequenced in the index based upon the key columns specified on the creation
of the index. When the optimizer matches a query to index key columns, it can use the index to help
satisfy query selection, ordering, grouping, or join requirements.
Typically, using an index also includes a table probe to provide access to columns needed to satisfy the
query that cannot be found as index keys. If all the columns necessary to satisfy the query can be found
as index keys, then the table probe is not required. The query uses index-only access. Avoiding the table
probe can be an important savings for a query. The I/O associated with a table probe is typically the more
expensive synchronous random I/O.
Visual Explain icon:

Radix index scan


A radix index scan operation is used to retrieve the rows from a table in a keyed sequence. Like a table
scan, all the rows in the index are sequentially processed, but the resulting row numbers are sequenced
based upon the key columns.
The sequenced rows can be used by the optimizer to satisfy a portion of the query request (such as
ordering or grouping). They can also be used to provide faster throughput by performing selection against
the index keys rather than all the rows in the table. Since the index I/Os only contain keys, typically more
rows can be paged into memory in one I/O than rows in a table with many columns.

Table 4. Radix index scan attributes


Data access method Radix index scan
Description Sequentially scan and process all the keys associated with the index.
Any selection is applied to every key value of the index before a table
row
Advantages • Only those index entries that match any selection continue to be
processed
• Potential to extract all the data from the index key values, thus
eliminating the need for a Table Probe
• Returns the rows back in a sequence based upon the keys of the
index

Considerations Generally requires a Table Probe to be performed to extract any


remaining columns required to satisfy the query. Can perform poorly
when many rows are selected because of the random I/O associated
with the Table Probe.

22 IBM i: Performance and Query Optimization


Table 4. Radix index scan attributes (continued)
Data access method Radix index scan
Likely to be used • When asking for or expecting only a few rows to be returned from
the index
• When sequencing the rows is required for the query (for example,
ordering or grouping)
• When the selection columns cannot be matched against the leading
key columns of the index

Example SQL statement


CREATE INDEX X1 ON Employee (LastName, WorkDept)

SELECT * FROM Employee


WHERE WorkDept BETWEEN 'A01' AND 'E01'
ORDER BY LastName
OPTIMIZE FOR 30 ROWS

Database Monitor and Plan QQRID 3001 Index Used, where QQKP (Index_Probe_Used) set to 'N'
Cache record indicating use will indicate an index scan operation. Preload indicated by QVPARPL =
'Y'. Distinct Probe indicated by QVC11 = 'Y'.

SMP parallel enabled Yes


Also referred to as Index Scan
Index Scan, Preload
Index Scan, Distinct
Index Scan Distinct, Preload
Index Scan, Key Selection

Visual Explain icon

Related reference
Effects of the ALWCPYDTA parameter on database performance
Some complex queries can perform better by using a sort or hashing method to evaluate the query
instead of using or creating an index.

Radix index probe


A radix index probe operation is used to retrieve the rows from a table in a keyed sequence. The main
difference between the radix index probe and the scan is that the rows returned are first identified by a
probe operation to subset them.
The optimizer attempts to match the columns used for some or all the selection against the leading keys
of the index. It then rewrites the selection into a series of ranges that can be used to probe directly into
the index key values. Only those keys from the series of ranges are paged into main memory.
The resulting row numbers generated by the probe can then be further processed by any remaining
selection against the index keys or a table probe operation. This method provides for quick access to only
the rows of the index that satisfy the selection.
The main function of a radix index probe is to provide quick selection against the index keys. In addition,
the row sequencing can be used to satisfy other portions of the query, such as ordering or grouping. Since

Database performance and query optimization 23


the index I/Os are only for rows that match the probe selection, no extraneous processing is performed on
rows that do not match. This savings in I/Os against rows that are not a part of the result set is one of the
primary advantages for this operation.

Table 5. Radix index probe attributes


Data access method Radix index probe
Description The index is quickly probed based upon the selection criteria that
were rewritten into a series of ranges. Only those keys that satisfy the
selection are used to generate a table row number.
Advantages • Only those index entries that match any selection continue to be
processed
• Provides quick access to the selected rows
• Potential to extract all the data from the index key values, thus
eliminating the need for a Table Probe
• Returns the rows back in a sequence based upon the keys of the
index

Considerations Generally requires a Table Probe to be performed to extract any


remaining columns required to satisfy the query. Can perform poorly
when many rows are selected because of the random I/O associated
with the Table Probe.
Likely to be used • When asking for or expecting only a few rows to be returned from the
index
• When sequencing the rows is required the query (for example,
ordering or grouping)
• When the selection columns match the leading key columns of the
index

Example SQL statement


CREATE INDEX X1 ON Employee (LastName, WorkDept)

SELECT * FROM Employee


WHERE WorkDept BETWEEN 'A01' AND 'E01'
AND LastName IN ('Smith', 'Jones', 'Peterson')
OPTIMIZE FOR ALL ROWS

Database Monitor and Plan QQRID 3001 Index Used


Cache record indicating use
where QQKP (Index_Probe_Used) set to 'Y' will indicate an index probe
operation.
Preload indicated by QVPARPL = 'Y'
Distinct Probe indicated by QVC11 = 'Y'

SMP parallel enabled Yes


Also referred to as Index Probe
Index Probe, Preload
Index Probe, Distinct
Index Probe Distinct, Preload
Index Probe, Key Positioning
Index Scan, Key Row Positioning

24 IBM i: Performance and Query Optimization


Table 5. Radix index probe attributes (continued)
Data access method Radix index probe
Visual Explain icon

The following example illustrates a query where the optimizer might choose the radix index probe access
method:

CREATE INDEX X1 ON Employee (LastName, WorkDept)

SELECT * FROM Employee


WHERE WorkDept BETWEEN 'A01' AND 'E01'
AND LastName IN ('Smith', 'Jones', 'Peterson')
OPTIMIZE FOR ALL ROWS

In this example, index X1 is used to position to the first index entry that matches the selection built
over both columns LastName and WorkDept. The selection is rewritten into a series of ranges that match
all the leading key columns used from the index X1. The probe is then based upon the composite
concatenated values for all the leading keys. The pseudo-SQL for this rewritten SQL might look as follows:

SELECT * FROM X1
WHERE X1.LeadingKeys BETWEEN 'JonesA01' AND 'JonesE01'
OR X1.LeadingKeys BETWEEN 'PetersonA01' AND 'PetersonE01'
OR X1.LeadingKeys BETWEEN 'SmithA01' AND 'SmithE01'

All the key entries that satisfy the probe operation are used to generate a row number for the table
associated with the index (for example, Employee). The row number is used by a Table Probe operation to
perform random I/O on the table to produce the results for the query. This processing continues until all
the rows that satisfy the index probe operation have been processed. In this example, all the index entries
processed and rows retrieved met the index probe criteria.
Additional selection might be added that cannot use an index probe, such as selection against columns
which are not leading key columns of the index. Then the optimizer performs an index scan operation
within the range of probed values. This process still allows for selection to be performed before the Table
Probe operation.
Related concepts
Nested loop join implementation
Db2 for i provides a nested loop join method. For this method, the processing of the tables in the join
are ordered. This order is called the join order. The first table in the final join order is called the primary
table. The other tables are called secondary tables. Each join table position is called a dial.
Related reference
Effects of the ALWCPYDTA parameter on database performance
Some complex queries can perform better by using a sort or hashing method to evaluate the query
instead of using or creating an index.

Encoded vector index


An encoded vector index is a permanent object that provides access to a table. This access is done by
assigning codes to distinct key values and then representing those values in a vector.
The size of the vector matches the number of rows in the underlying table. Each vector entry represents
the table row number in the same position. The codes generated to represent the distinct key values can
be 1 byte, 2 bytes, or 4 bytes in length. The key length depends upon the number of distinct values that

Database performance and query optimization 25


need to be represented in the vector. Because of their compact size and relative simplicity, the EVI can be
used to process large amounts of data efficiently.
An encoded vector index is used to represent the values stored in a table. However, the index itself
cannot be used to directly gain access to the table. Instead, the encoded vector index can only be used to
generate either a temporary row number list or a temporary row number bitmap. These temporary objects
can then be used with a table probe to specify the rows in the table that the query needs to process.
The main difference in the table probe using an encoded vector index vs. a radix index is that the I/O
paging can be asynchronous. The I/O can now be scheduled more efficiently to take advantage of groups
of selected rows. Large portions of the table can be skipped over where no rows are selected.
Visual explain icon:

Related concepts
Encoded vector indexes
An encoded vector index (EVI) is used to provide fast data access in decision support and query reporting
environments.
EVI maintenance
There are unique challenges to maintaining EVIs. The following table shows a progression of how EVIs are
maintained, the conditions under which EVIs are most effective, and where EVIs are least effective, based
on the EVI maintenance characteristics.

Encoded vector index RRN probe


A table probe operation is used to retrieve a specific row from a table based upon its row number. The
row number is provided to the table probe access method by some other operation that generates a row
number for the table.
The encoded vector index (EVI) RRN probe is an index only access method that is used to provide
selected columns by retrieving the value from the EVI instead of using a table probe to access the
table. Retrieving the value from the EVI should provide better I/O characteristics than the random I/Os
associated with a table probe operation.
This access method is used in conjunction with a radix index probe, radix index scan, or EVI probe
operation. The radix index probe, radix index scan, or EVI probe operation is used to select the rows and
then the RRN of the selected row is used to probe into EVIs to retrieve any selected values that were not
provided by the index used for selection. The EVI RRN probe can access multiple EVIs to provide selected
values.

Table 6. EVI RRN probe attributes


Data access method EVI RRN Probe
Description The encoded vector index (EVI) is quickly probed based upon the RRNs
provided by the underlying index access.
Advantages • Potential to extract all the data from the EVI index key values, thus
eliminating the need for a Table Probe
• Provides better paging characteristics than a Table Probe.

26 IBM i: Performance and Query Optimization


Table 6. EVI RRN probe attributes (continued)
Data access method EVI RRN Probe
Considerations • Only single key EVIs are considered for this implementation
• All selected columns must have a single column EVI created.
• The EVIs must fit in the query’s fair share of optimizer memory

Likely to be used • When the table row size is wide, the number of select columns is
small compared to the number of columns in the table and the query
requires a table probe to retrieve columns

Example SQL statement


CREATE ENCODED VECTOR INDEX EVI1 ON
Employee (WorkDept)
CREATE ENCODED VECTOR INDEX EVI2 ON
Employee (Salary)WITH 10000 DISTINCT VALUES
CREATE ENCODED VECTOR INDEX EVI3 ON
Employee (LASTNAME)WITH 100000 DISTINCT VALUES
CREATE INDEX IX1 ON Employee (Job)

SELECT LASTNAME, WORKDEPT, SALARY


FROM EMPLOYEE
WHERE JOB = ‘ANALYST’

Database Monitor and Plan A QQRID 3001 Index Used record for each EVI with QQRCOD = ‘I8’
Cache record indicating use
SMP parallel enabled Yes
Also referred to as Table Probe, Preload
Visual Explain icon

Prior to encoded vector index only access (EOA), the recommendation had been to only create EVIs for
column with low cardinality (small number of distinct values). This recommendation has now changed.
EVI RRN Probe can be used for columns with high cardinality (large number of distinct values). However,
when creating the EVI, the WITH integer DISTINCT VALUES clause should be used to set the initial size of
the codes appropriately and to minimize maintenance time if the database manager needs to use a larger
code. See the CREATE INDEX statement in the SQL Reference for more details.

Encoded vector index probe


The encoded vector index (EVI) is quickly probed based upon the selection criteria that were rewritten
into a series of ranges. It produces either a temporary row number list or bitmap.

Table 7. Encoded vector index probe attributes


Data access method Encoded vector index probe
Description The encoded vector index (EVI) is quickly probed based upon the
selection criteria that were rewritten into a series of ranges. It produces
either a temporary row number list or bitmap.

Database performance and query optimization 27


Table 7. Encoded vector index probe attributes (continued)
Data access method Encoded vector index probe
Advantages • Only those index entries that match any selection continue to be
processed
• Provides quick access to the selected rows
• Returns the row numbers in ascending sequence so that the Table
Probe can be more aggressive in pre-fetching the rows for its
operation

Considerations EVIs are usually built over a single key. The more distinct the column
is and the higher the overflow percentage, the less advantageous the
encoded vector index becomes. EVIs always require a Table Probe to be
performed on the result of the EVI probe operation.
Likely to be used • When the selection columns match the leading key columns of the
index
• When an encoded vector index exists and savings in reduced I/O
against the table justifies the extra cost. This cost includes probing
the EVI and fully populating the temporary row number list.

Example SQL statement


CREATE ENCODED VECTOR INDEX EVI1 ON
Employee (WorkDept)
CREATE ENCODED VECTOR INDEX EVI2 ON
Employee (Salary)
CREATE ENCODED VECTOR INDEX EVI3 ON
Employee (Job)

SELECT *
FROM Employee
WHERE WorkDept = 'E01' AND Job = 'CLERK'
AND Salary = 5000
OPTIMIZE FOR 99999 ROWS

Database Monitor and Plan


QQRID 3001 Index Used with QQRCOD='I5',
Cache record indicating use QQRID 3021 Bitmap Created and optionally
QQRID 3022 Bitmap Merge.

SMP parallel enabled Yes


Also referred to as Encoded Vector Index Probe, Preload
Visual Explain icon

Using the example above, the optimizer chooses to create a temporary row number bitmap for each of
the encoded vector indexes used by this query. Each bitmap only identifies those rows that match the
selection on the key columns for that index.
These temporary row number bitmaps are then merged together to determine the intersection of the rows
selected from each index. This intersection is used to form a final temporary row number bitmap used to
help schedule the I/O paging against the table for the selected rows.
The optimizer might choose to perform an index probe with a binary radix tree index if an index existed
over all three columns. The implementation choice is probably decided by the number of rows to be
returned and the anticipated cost of the I/O associated with each plan.

28 IBM i: Performance and Query Optimization


If few rows are returned, the optimizer probably chooses the binary radix tree index and performs the
random I/O against the table. However, selecting more rows causes the optimizer to use the EVIs,
because of the savings from the more efficiently scheduled I/O against the table.

Encoded vector index index-symbol table only access


The encoded vector index can also be used for index-symbol table only access.
The EVI can be used for more than generating a bitmap or row number list to provide an asynchronous I/O
map to the desired table rows. The EVI can also be used by two index-only access methods that can be
applied specific to the symbol table itself. These two index-only access methods are the EVI symbol table
scan and the EVI symbol table probe.
These two methods can be used with GROUP BY or DISTINCT queries that can be satisfied by the symbol
table. This symbol table-only access can be further employed in aggregate queries by adding INCLUDE
values to the encoded vector index.
The following information is a summary of the symbol table-only scan and probe access methods.
Use the following links to learn in-depth information.
Related concepts
Encoded vector indexes
An encoded vector index (EVI) is used to provide fast data access in decision support and query reporting
environments.
How the EVI works
EVIs work in different ways for costing and implementation.
Related reference
Index grouping implementation
There are two primary ways to implement grouping using an index: Ordered grouping and pre-
summarized processing.

Encoded vector index symbol table scan


An encoded vector index symbol table scan operation is used to retrieve the entries from the symbol table
portion of the index.
All entries (symbols) in the symbol table are sequentially scanned if a scan is chosen. The symbol table
can be used by the optimizer to satisfy GROUP BY or DISTINCT portions of a query request.
Selection is applied to every entry in the symbol table. The selection must be applied to the symbol table
keys unless the EVI was created as a sparse index, with a WHERE clause. In that case, a portion of the
selection is applied as the symbol table is built and maintained. The query request must include matching
predicates to use the sparse EVI.
All entries are retrieved directly from the symbol table portion of the index without any access to the
vector portion of the index. There is also no access to the records in the associated table over which the
EVI is built.

Encoded vector index INCLUDE aggregates


To enhance the ability of the EVI symbol table to provide aggregate answers, the symbol table can be
created to contain additional INCLUDE values. These are ready-made numeric aggregate results, such
as SUM, COUNT, AVG, or VARIANCE values requested over non-key data. These aggregates are specified
using the INCLUDE keyword on the CREATE ENCODED VECTOR INDEX request.
These included aggregates are maintained in real time as rows are inserted, updated, or deleted from the
corresponding table. The symbol table maintains these additional aggregate values in addendum to the
EVI keys for each symbol table entry. Because these are numeric results and finite in size, the symbol
table is still a desirable compact size.
These included aggregates are over non-key columns in the table where the grouping is over the
corresponding EVI symbol table defined keys. The aggregate can be over a single column or a derivation.

Database performance and query optimization 29


Table 8. Encoded vector index symbol table scan attributes
Data access method Encoded vector index symbol table scan
Description Sequentially scan and process all the symbol table entries associated
with the index. When there is selection (WHERE clause), it is applied to
every entry in the symbol table. An exception is made in the case of a
sparse EVI, where the selection is applied as the index is created and
maintained. Selected entries are retrieved directly without any access
to the vector or the associated table.
Advantages • Pre-summarized results are readily available
• Only processes the unique values in the symbol table, avoiding
processing table records.
• Extract all the data from the index unique key values or INCLUDE
values, thus eliminating the need for a Table Probe or vector scan.
• With INCLUDE, provides ready-made numeric aggregates, eliminating
the need to access corresponding table rows to perform the
aggregation

Considerations Dramatic performance improvement for grouping queries where the


resulting number of groups is relatively small compared to the number
of records in the underlying table. Can perform poorly when there
are many groups involved such that the symbol table is large. Poor
performance is even more likely if a large portion of the symbol table
has been put into the overflow area.
Dramatic performance improvement for grouping queries when the
aggregate is specified as an INCLUDE value of the symbol table.

Likely to be used • When asking for GROUP BY, DISTINCT, COUNT, or COUNT DISTINCT
from a single table and the referenced columns are in the key
definition.
• When the number of unique values in the columns of the key
definition is small relative to the number of records in the underlying
table.
• When there is no selection (WHERE clause) within the query or the
selection does not reduce the result set much.
• When the symbol table key satisfies the GROUP BY, and requested
aggregates, like SUM or COUNT, are specified as INCLUDE values.
• when the query is run with commitment control *NONE or *CHG.

30 IBM i: Performance and Query Optimization


Table 8. Encoded vector index symbol table scan attributes (continued)
Data access method Encoded vector index symbol table scan
Example SQL statement
CREATE ENCODED VECTOR INDEX EVI1 ON Sales (Region)

Example 1

SELECT Region, count(*)


FROM Sales
GROUP BY Region
OPTIMIZE FOR ALL ROWS

Example 2

SELECT DISTINCT Region


FROM Sales
OPTIMIZE FOR ALL ROWS

Example 3

SELECT COUNT(DISTINCT Region)


FROM Sales

Example 4 uses the INCLUDE option. The sums of revenue and cost of
goods per sales region is maintained in real time.

CREATE ENCODED VECTOR INDEX EVI2 ON Sales(Region)


INCLUDE(SUM(SALES))
SELECT Region, SUM(SALEs)
FROM Sales
GROUP BY Region

Database Monitor and Plan QQRID 3001 Index Used


Cache record indicating use
where QQC15 = 'E' AND QQRCOD = 'I2'

Also referred to as Encoded Vector Index Symbol Table Scan, Preload


Visual Explain icon

Related concepts
Encoded vector indexes
An encoded vector index (EVI) is used to provide fast data access in decision support and query reporting
environments.
How the EVI works
EVIs work in different ways for costing and implementation.
Related reference
Index grouping implementation

Database performance and query optimization 31


There are two primary ways to implement grouping using an index: Ordered grouping and pre-
summarized processing.

Encoded vector index symbol table probe


An encoded vector index symbol table probe operation is used to retrieve entries from the symbol table
portion of the index. Scanning the entire symbol table is not necessary.
The symbol table can be used by the optimizer to satisfy GROUP BY or DISTINCT portions of a query
request.
The optimizer attempts to match the columns used for some or all the selection against the leading keys
of the EVI index. It then rewrites the selection into a series of ranges that can be used to probe directly
into the symbol table. Only those symbol table pages from the series of ranges are paged into main
memory.
The resulting symbol table entries generated by the probe operation can then be further processed by
any remaining selection against EVI keys. This strategy provides for quick access to only the entries of the
symbol table that satisfy the selection.
Like an encoded vector symbol table scan, a symbol table probe can return ready-made aggregate results
if INCLUDE is specified when the EVI is created.
All entries are retrieved directly from the symbol table portion of the index without any access to the
vector portion of the index. In addition, it is unnecessary to access the records in the associated table
over which the EVI is built.

Table 9. Encoded vector index symbol table probe attributes


Data access method Encoded vector index symbol table probe
Description
Advantages Probe the symbol table entries associated with the index. When there is
selection (WHERE clause), it is applied to every entry in the symbol
table that meets the probe criteria. If there are sparse EVIs, the
selection is applied as the EVI is created and maintained. Selected
entries are retrieved directly without any access to the vector or the
associated table.
Considerations • Pre-summarized results are readily available
• Only processes the unique values in the symbol table, avoiding
processing table records.
• Extracts all the data from the index unique key values or include
values, or both, thus eliminating the need for a table probe or vector
scan
• With INCLUDE, provides ready-made numeric aggregates, eliminating
the need to access corresponding table rows to perform the
aggregation

32 IBM i: Performance and Query Optimization


Table 9. Encoded vector index symbol table probe attributes (continued)
Data access method Encoded vector index symbol table probe
Likely to be used • When asking for GROUP BY, DISTINCT, COUNT, or COUNT DISTINCT
from a single table and the referenced columns are in the key
definition.
• When the number of unique values in the columns of the key
definition is small relative to the number of records in the underlying
table.
• When there is selection (WHERE clause) that reduces the selection
from the Symbol Table and the WHERE clause involves leading,
probable keys.
• When the symbol table key satisfies the GROUP BY and the WHERE
clause reduces selection to the leading keys, and aggregates are
specified as INCLUDE values.
• When the query is run with commitment control *NONE or *CHG.

Example SQL statement


CREATE ENCODED VECTOR INDEX EVI1 ON Sales (Region)

Example 1

SELECT Region, COUNT(*)


FROM Sales
WHERE Region in ('Quebec', 'Manitoba')
GROUP BY Region
OPTIMIZE FOR ALL ROWS

Example 2

CREATE ENCODED VECTOR INDEX EVI2 ON Sales(Region)


INCLUDE(SUM(SALES))

SELECT Region, SUM(SALES)


FROM Sales
WHERE Region = ’PACIFIC’
GROUP BY Region

Database Monitor and Plan


QQRID 3001 Index Used
Cache record indicating use where QQC15 = 'E' AND QQRCOD = 'I2' AND QQKP = 'Y'

Also referred to as Encoded Vector Index Table Probe, Preload


Visual Explain icon

Related concepts
Encoded vector indexes
An encoded vector index (EVI) is used to provide fast data access in decision support and query reporting
environments.
How the EVI works

Database performance and query optimization 33


EVIs work in different ways for costing and implementation.
Related reference
Index grouping implementation
There are two primary ways to implement grouping using an index: Ordered grouping and pre-
summarized processing.

Temporary objects and access methods


Temporary objects are created by the optimizer in order to process a query. In general, these temporary
objects are internal objects and cannot be accessed by a user.

Table 10. Temporary object data access methods


Temporary create objects Scan operations Probe operations
Temporary hash table Hash table scan Hash table probe
Temporary sorted list Sorted list scan Sorted list probe
Temporary distinct sorted list Sorted list scan N/A
Temporary list List scan N/A
Temporary values list Values list scan N/A
Temporary row number list Row number list scan Row number list probe
Temporary bitmap Bitmap scan Bitmap probe
Temporary index Temporary index scan Temporary index probe
Temporary buffer Buffer scan N/A
Queue N/A N/A
Array unnest temporary table Temporary table scan N/A
Temporary Indexed List Temporary Indexed List Scan and N/A
Index Merge
Window Window scan N/A

Temporary hash table


The temporary hash table is a temporary object that allows the optimizer to collate the rows based upon
a column or set of columns. The hash table can be either scanned or probed by the optimizer to satisfy
different operations of the query.
A temporary hash table is an efficient data structure because the rows are organized for quick and easy
retrieval after population has occurred. The hash table remains resident within main memory to avoid any
I/Os associated with either the scan or probe against the temporary object. The optimizer determines
the optimal hash table size based on the number of unique column combinations used as keys for the
creation.
Additionally the hash table can be populated with all the necessary columns to satisfy any further
processing. This population avoids any random I/Os associated with a table probe operation.
However, the optimizer can selectively include columns in the hash table when the calculated size
exceeds the memory pool storage available for the query. In these cases, a table probe operation is
required to recollect the missing columns from the hash table before the selected rows can be processed.
The optimizer also can populate the hash table with distinct values. If the query contains grouping or
distinct processing, then all the rows with the same key value are not required in the hash table. The rows
are still collated, but the distinct processing is performed during the population of the hash table itself.
This method allows a simple scan on the result in order to complete the grouping or distinct operation.

34 IBM i: Performance and Query Optimization


A temporary hash table is an internal data structure and can only be created by the database manager
Visual explain icon:

Hash table scan


During a hash table scan operation, the entire temporary hash table is scanned and all the entries
contained within the hash table are processed.
The optimizer considers a hash table scan when the data values need to be collated together, but
sequencing of the data is not required. A hash table scan allows the optimizer to generate a plan that
takes advantage of any non-join selection while creating the temporary hash table.
An additional benefit is that the temporary hash table data structure will typically cause the table
data to remain resident within main memory after creation. Resident table data reduces paging on the
subsequent hash table scan operation.

Table 11. Hash table scan attributes


Data access method Hash table scan
Description Read all the entries in a temporary hash table. The hash table can
perform distinct processing to eliminate duplicates. Or the temporary
hash table can collate all the rows with the same value together.
Advantages • Reduces the random I/O to the table associated with longer running
queries that might otherwise use an index to collate the data
• Selection can be performed before generating the hash table to
subset the number of rows in the temporary object

Considerations Used for distinct or group by processing. Can perform poorly when
the entire hash table does not stay resident in memory as it is being
processed.
Likely to be used • When the use of temporary results is allowed by the query
environmental parameter (ALWCPYDTA)
• When the data is required to be collated based upon a column or
columns for distinct or grouping

Example SQL statement


SELECT COUNT(*), FirstNme FROM Employee
WHERE WorkDept BETWEEN 'A01' AND 'E01'
GROUP BY FirstNme

Database Monitor and Plan


QQRID 3023 Temp Hash Table Created
Cache record indicating use where QVC1F (HashTable_ReasonCode) = 'G'

SMP parallel enabled Yes


Also referred to as Hash Scan, Preload
Hash Table Scan Distinct
Hash Table Scan Distinct, Preload

Database performance and query optimization 35


Table 11. Hash table scan attributes (continued)
Data access method Hash table scan
Visual Explain icon

Hash table probe


A hash table probe operation is used to retrieve rows from a temporary hash table based upon a probe
lookup operation.
The optimizer initially identifies the keys of the temporary hash table from the join criteria specified in the
query. When the hash table is probed, the values used to probe into the hash table are extracted from the
join-from criteria specified in the selection.
These values are sent through the same hashing algorithm used to populate the temporary hash table.
They determine if any rows have a matching equal value. All the matching join rows are then returned to
be further processed by the query.

Table 12. Hash table probe attributes


Data access method Hash table probe
Description The temporary hash table is quickly probed based upon the join
criteria.
Advantages • Provides quick access to the selected rows that match probe criteria
• Reduces the random I/O to the table associated with longer running
queries that use an index to collate the data
• Selection can be performed before generating the hash table to
subset the number of rows in the temporary object

Considerations Used to process equal join criteria. Can perform poorly when the entire
hash table does not stay resident in memory as it is being processed.
Likely to be used • When the use of temporary results is allowed by the query
environmental parameter (ALWCPYDTA)
• When the data is required to be collated based upon a column or
columns for join processing
• The join criteria was specified using an equals (=) operator

Example SQL statement


SELECT * FROM Employee XXX, Department YYY
WHERE XXX.WorkDept = YYY.DeptNo
OPTIMIZE FOR ALL ROWS

Database Monitor and Plan


QQRID 3023 Temp Hash Table Created
Cache record indicating use where QVC1F (HashTable_ReasonCode) = 'J'

SMP parallel enabled Yes


Also referred to as Hash Table Probe, Preload
Hash Table Probe Distinct
Hash Table Probe Distinct, Preload

36 IBM i: Performance and Query Optimization


Table 12. Hash table probe attributes (continued)
Data access method Hash table probe
Visual Explain icon

The hash table probe access method is considered when determining the implementation for a secondary
table of a join. The hash table is created with the key columns that match the equal selection or join
criteria for the underlying table.
The hash table probe allows the optimizer to choose the most efficient implementation in selecting rows
from the underlying table, without regard for join criteria. This single pass through the underlying table
can now use a table scan or existing index to select the rows needed for the hash table population.
Since hash tables are constructed so that most of the hash table remains resident within main memory,
the I/O associated with a hash probe is minimal. Additionally, if the hash table was populated with all
necessary columns from the underlying table, no additional table probe is required to finish processing
this table. This method causes further I/O savings.
Related concepts
Nested loop join implementation
Db2 for i provides a nested loop join method. For this method, the processing of the tables in the join
are ordered. This order is called the join order. The first table in the final join order is called the primary
table. The other tables are called secondary tables. Each join table position is called a dial.

Temporary sorted list


The temporary sorted list is a temporary object that allows the optimizer to sequence rows based upon
a column or set of columns. The sorted list can be either scanned or probed by the optimizer to satisfy
different operations of the query.
A temporary sorted list is a data structure where the rows are organized for quick and easy retrieval after
population has occurred. During population, the rows are copied into the temporary object and then a
second pass is made through the temporary object to perform the sort.
In order to optimize the creation of this temporary object, minimal data movement is performed while the
sort is processed. It is not as efficient to probe a temporary sorted list as it is to probe a temporary hash
table.
Additionally, the sorted list can be populated with all the necessary columns to satisfy any further
processing. This population avoids any random I/Os associated with a table probe operation.
However, the optimizer can selectively include columns in the sorted list when the calculated size
exceeds the memory pool storage available for this query. In those cases, a table probe operation is
required to recollect the missing columns from the sorted list before the selected rows can be processed.
A temporary sorted list is an internal data structure and can only be created by the database manager.
Visual explain icon:

Database performance and query optimization 37


Sorted list scan
During a sorted list scan operation, the entire temporary sorted list is scanned and all the entries
contained within the sorted list are processed.
A sorted list scan is considered when the data values need to be sequenced. A sorted list scan allows
the optimizer to generate a plan that can take advantage of any non-join selection while creating the
temporary sorted list.
An additional benefit is that the data structure will usually cause the table data within the sorted list to
remain resident within main memory after creation. This resident data reduces paging on the subsequent
sorted list scan operation.

Table 13. Sorted list scan attributes


Data access method Sorted list scan
Description Read all the entries in a temporary sorted list. The sorted list can
perform distinct processing to eliminate duplicate values or take
advantage of the temporary sorted list to sequence all the rows.
Advantages • Reduces the random I/O to the table associated with longer running
queries that would otherwise use an index to sequence the data.
• Selection can be performed prior to generating the sorted list to
subset the number of rows in the temporary object

Considerations Used to process ordering or distinct processing. Can perform poorly


when the entire sorted list does not stay resident in memory as it is
being populated and processed.
Likely to be used • When the use of temporary results is allowed by the query
environmental parameter (ALWCPYDTA)
• When the data is required to be ordered based upon a column or
columns for ordering or distinct processing

Example SQL statement


CREATE INDEX X1 ON Employee (LastName, WorkDept)

SELECT * FROM Employee


WHERE WorkDept BETWEEN 'A01' AND 'E01'
ORDER BY FirstNme
OPTIMIZE FOR ALL ROWS

Database Monitor and Plan QQRID 3003 Query Sort. There is no specific field that indicates
Cache record indicating use whether or not the sorted list was used for a scan or a probe. Refer
to Visual Explain diagram for query implementation details.

SMP parallel enabled No


Also referred to as Sorted List Scan, Preload
Sorted List Scan Distinct
Sorted List Scan Distinct, Preload

Visual Explain icon

38 IBM i: Performance and Query Optimization


Sorted list probe
A sorted list probe operation is used to retrieve rows from a temporary sorted list based upon a probe
lookup operation.
The optimizer initially identifies the temporary sorted list keys from the join criteria specified in the query.
The values used to probe into the temporary sorted list are extracted from the join-from criteria specified
in the selection. Those values are used to position within the sorted list in order to determine if any rows
have a matching value. All the matching join rows are then returned to be further processed by the query.

Table 14. Sorted list probe attributes


Data access method Sorted list probe
Description The temporary sorted list is quickly probed based upon the join criteria.
Advantages • Provides quick access to the selected rows that match probe criteria
• Reduces the random I/O to the table associated with longer running
queries that otherwise use an index to collate the data
• Selection can be performed before generating the sorted list to
subset the number of rows in the temporary object

Considerations Used to process non-equal join criteria. Can perform poorly when
the entire sorted list does not stay resident in memory as it is being
populated and processed.
Likely to be used • When the use of temporary results is allowed by the query
environmental parameter (ALWCPYDTA)
• When the data is required to be collated based upon a column or
columns for join processing
• The join criteria was specified using a non-equals operator

Example SQL statement


SELECT * FROM Employee XXX, Department YYY
WHERE XXX.WorkDept > YYY.DeptNo
OPTIMIZE FOR ALL ROWS

Database Monitor and Plan QQRID 3003 Query Sort. There is no specific field that indicates
Cache record indicating use whether or not the sorted list was used for a scan or a probe. Refer
to Visual Explain diagram for query implementation details.

SMP parallel enabled Yes


Also referred to as Sorted List Probe, Preload
Sorted List Probe Distinct
Sorted List Probe Distinct, Preload

Visual Explain icon

The sorted list probe access method is considered when determining the implementation for a secondary
table of a join. The sorted list is created with the key columns that match the non-equal join criteria for
the underlying table. The optimizer chooses the most efficient implementation to select the rows from the
underlying table without regard to any join criteria. This single pass through the underlying table can use a
Table Scan or an existing index to select the rows needed to populate the sorted list.

Database performance and query optimization 39


Since sorted lists are constructed so that most of the temporary object remains resident within main
memory, the sorted list I/O is minimal. If the sorted list was populated with all necessary table columns,
no additional Table Probe is required to finish processing the table, causing further I/O savings.
Related concepts
Nested loop join implementation
Db2 for i provides a nested loop join method. For this method, the processing of the tables in the join
are ordered. This order is called the join order. The first table in the final join order is called the primary
table. The other tables are called secondary tables. Each join table position is called a dial.

Temporary distinct sorted list


A temporary distinct sorted list combines the features of the temporary hash table and the temporary
sorted list.
Like the hash table, the temporary distinct sorted list allows the optimizer to collate the rows based on a
column or set of columns. Like the sorted list, the temporary distinct sorted list also allows the optimizer
to sequence the rows.
A temporary distinct sorted list contains a hash table data structure set up for efficient access to
aggregate rows during population. In addition, a binary tree data structure is maintained over the hash
table data structure so that the data can be accessed in sequence. The sorted aspect of the data structure
allows for the efficient computation of super-aggregate rows in SQL statements that contain GROUP BY
ROLLUP.
A temporary sorted aggregate hash table is an internal data structure and can only be created by the
database manager.
Visual explain icon:

Sorted list scan


During the sorted list scan, the entire temporary distinct sorted list is scanned and all the entries
contained within the temporary are processed.
The optimizer uses the sorted list scan when the data values need to be aggregated and sequenced.
The optimizer generates this plan that can take advantage of any non-join selection while creating the
temporary distinct sorted list. The data structure of the temporary distinct sorted list will typically cause
the table data to remain resident within main memory after creation. This memory-resident data reduces
paging on the subsequent sorted list scan.

Table 15. Sorted list scan attributes


Data access method Sorted list scan
Description Reads all the entries in a temporary distinct sorted list
Advantages • Allows efficient computation of ROLLUP super-aggregate rows.
• Reduces the random I/O to the table associated with longer running
queries that might otherwise use an index to collate the data.
• Selection can be performed before generating the distinct sorted list
to subset the number of rows in the temporary object.

40 IBM i: Performance and Query Optimization


Table 15. Sorted list scan attributes (continued)
Data access method Sorted list scan
Considerations Used for GROUP BY ROLLUP processing, Can perform poorly when the
entire temporary object does not stay resident in memory as it is being
processed.
Likely to be used • When the use of temporary results is allowed in the query
environmental parameter (ALWCPYDTA)
• When a GROUP BY ROLLUP is in the SQL statement

Messages indicating use N/A


SMP parallel enabled Yes
Also referred to as N/A
Visual Explain icon

Temporary list
The temporary list is a temporary object that allows the optimizer to store intermediate results of a query.
The list is an unsorted data structure that is used to simplify the operation of the query. Since the list does
not have any keys, the rows within the list can only be retrieved by a sequential scan operation.
The temporary list can be used for various reasons, some of which include an overly complex view or
derived table, Symmetric Multiprocessing (SMP) or to prevent a portion of the query from being processed
multiple times.
A temporary list is an internal data structure and can only be created by the database manager.
Visual explain icon:

List scan
The list scan operation is used when a portion of the query is processed multiple times, but no key
columns can be identified. In these cases, that portion of the query is processed once and its results
are stored within the temporary list. The list can then be scanned for only those rows that satisfy any
selection or processing contained within the temporary object.

Table 16. List scan attributes


Data access method List scan
Description Sequentially scan and process all the rows in the temporary list.

Database performance and query optimization 41


Table 16. List scan attributes (continued)
Data access method List scan
Advantages • The temporary list and list scan can be used by the optimizer to
minimize repetition of an operation or to simplify the optimizer logic
flow.
• Selection can be performed before generating the list to subset the
number of rows in the temporary object.

Considerations Used to prevent portions of the query from being processed multiple
times when no key columns are required to satisfy the request.
Likely to be used • When the use of temporary results is allowed by the query
environmental parameter (ALWCPYDTA).
• When Db2 symmetric multiprocessing is used for the query.

Example SQL statement


SELECT * FROM Employee XXX, Department YYY
WHERE XXX.LastName IN ('Smith', 'Jones', 'Peterson')
AND YYY.DeptNo BETWEEN 'A01' AND 'E01'
OPTIMIZE FOR ALL ROWS

Database Monitor and Plan QQRID 3004 Temp Table


Cache record indicating use
SMP parallel enabled Yes
Also referred to as List Scan, Preload
Visual Explain icon

Using the example above, the optimizer chose to create a temporary list to store the selected rows from
the DEPARTMENT table. Since there is no join criteria, a Cartesian product join is performed between
the two tables. To prevent the join from scanning all the rows of the DEPARTMENT table for each join
possibility, the selection against the DEPARTMENT table is performed once. The results are stored in the
temporary list. The temporary list is then scanned for the Cartesian product join.

Temporary values list


The temporary values list allows the optimizer to store rows of data specified in a VALUES clause of a
SELECT or CREATE VIEW statement.
The list is an unsorted data structure that is used to simplify the operation of the query. Since the list does
not have any keys, the rows within the list can only be retrieved by a sequential scan operation.
A temporary values list is an internal data structure and can only be created by the database manager.
Visual explain icon:

42 IBM i: Performance and Query Optimization


Values list scan
During a values list scan operation, the entire temporary values list is scanned and all the rows of data are
processed.

Table 17. Values list scan attributes


Data access method Values list scan
Description Sequentially scan and process all the rows of data in the temporary
values list.
Advantages The temporary values list and values list scan can be used by the
optimizer to simplify the optimizer logic flow.
Likely to be used When a VALUES clause is specified in the from-clause of an SQL
fullselect
Example SQL statement
SELECT EMPNO, 'empprojact'
FROM EMPPROJACT
WHERE PROJNO IN('MA2100', 'MA2110', 'MA2112')
UNION
VALUES ('NEWAAA', 'new'), ('NEWBBB', 'new')

Database Monitor and Plan


QQRID 3000 where QVQTBL = '*VALUES'
Cache record indicating use
SMP parallel enabled Yes
Visual Explain icon

Temporary row number list


The temporary row number list, also referred to as an RRN List, is a temporary object that allows the
optimizer to sequence rows based upon their row address (their row number). The row number list can be
either scanned or probed by the optimizer to satisfy different operations of the query.
A temporary row number list is a data structure where the rows are organized for quick and efficient
retrieval. The row number list only contains the row number for the associated row. Since no table data
is present, a table probe operation is typically associated with it in order to retrieve the underlying table
data. Because the row numbers are sorted, the random I/O associated with the table probe operation is
performed more efficiently. The database manager performs pre-fetch or look-ahead logic to determine if
multiple rows are located on adjacent pages. If so, the table probe requests a larger I/O to bring the rows
into main memory more efficiently.
A temporary row number list is an internal data structure and can only be created by the database
manager.
Visual explain icon:

Row number list scan


The entire temporary row number list is scanned and all the row addresses contained within the row
number list are processed. The optimizer considers this plan when there is an applicable encoded vector

Database performance and query optimization 43


index or if the index probe or scan random I/O can be reduced. The random I/O can be reduced by first
preprocessing and sorting the row numbers associated with the Table Probe.
The use of a row number list scan allows the optimizer to generate a plan that can take advantage of
multiple indexes to match up to different portions of the query.
An additional benefit is that the data structure of the temporary row number list guarantees that the row
numbers are sorted. It closely mirrors the row number layout of the table data, ensuring that the table
paging never visits the same page of data twice. This results in increased I/O savings for the query.
A row number list scan is identical to a bitmap scan operation. The only difference is that the list scan is
over a list of row addresses while the bitmap scan is over a bitmap representing the addresses.

Table 18. Row number list scan


Data access method Row number list scan
Description Sequentially scan and process all the row numbers in the temporary
row number list. The sorted row numbers can be merged with other
temporary row number lists or can be used as input into a Table Probe
operation.
Advantages • The temporary row number list only contains address, no data, so the
temporary can be efficiently scanned within memory.
• The row numbers contained within the temporary object are sorted to
provide efficient I/O processing to access the underlying table.
• Selection is performed as the row number list is generated to subset
the number of rows in the temporary object.

Considerations Since the row number list contains only the addresses of the selected
rows in the table, a separate Table Probe fetches the table rows.
Likely to be used • When the use of temporary results is allowed by the query
environmental parameter (ALWCPYDTA).
• When the cost of sorting of the row number is justified by the more
efficient I/O that can be performed during the Table Probe operation.
• When multiple indexes over the same table need to be combined in
order to minimize the number of selected rows.

Example SQL statement


CREATE INDEX X1 ON Employee (WorkDept)
CREATE ENCODED VECTOR INDEX EVI2 ON
Employee (Salary)
CREATE ENCODED VECTOR INDEX EVI3 ON
Employee (Job)

SELECT * FROM Employee


WHERE WorkDept = 'E01' AND Job = 'CLERK'
AND Salary = 5000
OPTIMIZE FOR 99999 ROWS

Database Monitor and Plan QQRID 3001 and QQRID 3021 records for each index used.
Cache record indicating use
The QQC11 field in the 3021 record will be 'L'.
A QQRID 3000 record with QQC11 (Skip_Sequential_Table_Scan) = 'Y'.
Optionally, QQRID 3022 records if bitmap merging occurred.

SMP parallel enabled Yes


Also referred to as Row Number List Scan, Preload; RRN Scan; RRN Scan, Preload

44 IBM i: Performance and Query Optimization


Table 18. Row number list scan (continued)
Data access method Row number list scan
Visual Explain icon

Using the example above, the optimizer created a temporary row number list for each of the indexes used
by this query. These indexes included a radix index and two encoded vector indexes. Each index row
number list was scanned and merged into a final composite row number list representing the intersection
of all the index row number lists. The final row number list is then used by the Table Probe to determine
which rows are selected and processed for the query results.

Row number list probe


A row number list probe is used to test row numbers generated by a separate operation against the
selected rows of a temporary row number list. The row numbers can be generated by any operation that
constructs a row number for a table. That row number is then used to probe into a temporary row number
list to determine if it matches the selection used to generate the list.
The use of a row number list probe operation allows the optimizer to generate a plan that can take
advantage of any sequencing provided by an index, but still use the row number list to perform additional
selection before any Table probe operations.
A row number list probe is identical to a bitmap probe operation. The only difference is that the list probe
is over a list of row addresses while the bitmap probe is over a bitmap representing the addresses.

Table 19. Row number list probe


Data access method Row number list probe
Description The temporary row number list is quickly probed based upon the row
number generated by a separate operation.
Advantages • The temporary row number list only contains a row address, no data,
so the temporary can be efficiently probed within memory.
• The row numbers represented within the row number list are sorted
to provide efficient lookup processing to test the underlying table.
• Selection is performed as the row number list is generated to subset
the number of selected rows in the temporary object.

Considerations Used when the query contains ordering and additional selection that
can be satisfied by additional indexes. Since the row number list
contains only the addresses of the selected rows in the table, a
separate Table Probe fetches the table rows.
Likely to be used • When the use of temporary results is allowed by the query
environmental parameter (ALWCPYDTA).
• When the cost of creating and probing the row number list is justified
by reducing the number of Table Probe operations that must be
performed.
• When multiple indexes over the same table need to be combined in
order to minimize the number of selected rows.

Database performance and query optimization 45


Table 19. Row number list probe (continued)
Data access method Row number list probe
Example SQL statement
CREATE INDEX X1 ON Employee (WorkDept)
CREATE ENCODED VECTOR INDEX EVI2 ON
Employee (Salary)
CREATE ENCODED VECTOR INDEX EVI3 ON
Employee (Job)

SELECT * FROM Employee


WHERE WorkDept = 'E01' AND Job = 'CLERK'
AND Salary = 5000
ORDER BY WorkDept

Database Monitor and Plan QQRID 3001 and QQRID 3021 records for each index used.
Cache record indicating use
The QQC11 field in the 3021 record will be 'L'.
Optionally, QQRID 3022 records if bitmap merging occurred.

SMP parallel enabled Yes


Also referred to as Row Number List Probe, Preload; RRN Probe; RRN Probe, Preload
Visual Explain icon

Using the example above, the optimizer created a temporary row number list for each of the encoded
vector indexes. Additionally, an index probe operation was performed against the radix index X1 to satisfy
the ordering requirement. Since the ORDER BY requires that the resulting rows be sequenced by the
WorkDept column, the row number list cannot be scanned for the selected rows.
However, the temporary row number list can be probed using a row address extracted from the index X1
used to satisfy the ordering. By probing the list with the row address extracted from the index probe, the
sequencing of the keys in the index X1 is preserved. The row can still be tested against the selected rows
within the row number list.

Temporary bitmap
The temporary bitmap is a temporary object that allows the optimizer to sequence rows based upon their
row address (their row number). The bitmap can be either scanned or probed by the optimizer to satisfy
different operations of the query.
A temporary bitmap is a data structure that uses a bitmap to represent all the row numbers for a table.
Since each row is represented by a separate bit, all the rows within a table can be represented in a fairly
condensed form. When a row is selected, the bit within the bitmap that corresponds to the selected row is
set on. After the temporary bitmap is populated, all the selected rows can be retrieved in a sorted manner
for quick and efficient retrieval. The temporary bitmap only represents the row number for the associated
selected rows.
No table data is present within the temporary bitmap. A table probe operation is typically associated with
the bitmap in order to retrieve the underlying table data. Because the bitmap is by definition sorted, the
random I/O associated with the table probe operation can be performed more efficiently. The database
manager performs pre-fetch or look-ahead logic to determine if multiple rows are located on adjacent
pages. If so, the table probe requests a larger I/O to bring the rows into main memory more efficiently.
A temporary bitmap is an internal data structure and can only be created by the database manager.
Visual explain icon:

46 IBM i: Performance and Query Optimization


Bitmap scan
During a bitmap scan operation, the entire temporary bitmap is scanned and all the row addresses
contained within the bitmap are processed. The optimizer considers this plan when there is an applicable
encoded vector index or if the index probe or scan random I/O can be reduced. The random I/O can be
reduced by first preprocessing and sorting the row numbers associated with the Table Probe.
The use of a bitmap scan allows the optimizer to generate a plan that can take advantage of multiple
indexes to match up to different portions of the query.
An additional benefit is that the data structure of the temporary bitmap guarantees that the row numbers
are sorted. It closely mirrors the row number layout of the table data, ensuring that the table paging never
visits the same page of data twice. This results in increased I/O savings for the query.
A bitmap scan is identical to a row number list scan operation. The only difference is that the list scan is
over a list of row addresses while the bitmap scan is over a bitmap representing the addresses.

Table 20. Bitmap scan attributes


Data access method Bitmap scan attributes
Description Sequentially scan and process all the row numbers in the temporary
bitmap. The sorted row numbers can be merged with other temporary
bitmaps or can be used as input into a Table Probe operation.
Advantages • The temporary bitmap only contains a reference to a row address, no
data, so the temporary can be efficiently scanned within memory.
• The row numbers represented within the temporary object are sorted
to provide efficient I/O processing to access the underlying table.
• Selection is performed as the bitmap is generated to subset the
number of selected rows in the temporary object.

Considerations Since the bitmap contains only the addresses of the selected rows in
the table, a separate Table Probe fetches the table rows.
Likely to be used • When the use of temporary results is allowed by the query
environmental parameter (ALWCPYDTA).
• When the cost of sorting of the row numbers is justified by the more
efficient I/O that can be performed during the Table Probe operation.
• When multiple indexes over the same table need to be combined in
order to minimize the number of selected rows.

Example SQL statement


CREATE INDEX X1 ON Employee (WorkDept)
CREATE ENCODED VECTOR INDEX EVI2 ON
Employee (Salary)
CREATE ENCODED VECTOR INDEX EVI3 ON
Employee (Job)

SELECT * FROM Employee


WHERE WorkDept = 'E01' AND Job = 'CLERK'
AND Salary = 5000
OPTIMIZE FOR 99999 ROWS

Database performance and query optimization 47


Table 20. Bitmap scan attributes (continued)
Data access method Bitmap scan attributes
Database Monitor and Plan QQRID 3001 and QQRID 3021 records for each index used.
Cache record indicating use
The QQC11 field in the 3021 record will be 'B'.
A QQRID 3000 record with QQC11 (Skip_Sequential_Table_Scan) = 'Y'.
Optionally, QQRID 3022 records if bitmap merging occurred.

SMP parallel enabled Yes


Also referred to as Bitmap Scan, Preload
Row Number Bitmap Scan
Row Number Bitmap Scan, Preload
Skip Sequential Scan

Visual Explain icon

Using the example above, the optimizer created a temporary bitmap for each of the indexes used by
this query. These indexes included a radix index and two encoded vector indexes. Each index temporary
bitmap was scanned and merged into a final composite bitmap representing the intersection of all the
index temporary bitmaps. The final bitmap is then used by the Table Probe operation to determine which
rows are selected and processed for the query results.

Bitmap probe
A bitmap probe operation is used to test row numbers generated by a separate operation against
the selected rows of a temporary bitmap. The row numbers can be generated by any operation that
constructs a row number for a table. That row number is then used to probe into a temporary bitmap to
determine if it matches the selection used to generate the bitmap.
The use of a bitmap probe operation allows the optimizer to generate a plan that can take advantage of
any sequencing provided by an index, but still use the bitmap to perform additional selection before any
Table Probe operations.
A bitmap probe is identical to a row number list probe operation. The only difference is that the list probe
is over a list of row addresses while the bitmap probe is over a bitmap representing the addresses.

Table 21. Bitmap probe attributes


Data access method Bitmap probe attributes
Description The temporary bitmap is quickly probed based upon the row number
generated by a separate operation.
Advantages • The temporary bitmap only contains a reference to a row address, no
data, so the temporary can be efficiently probed within memory.
• The row numbers represented within the bitmap are sorted to
provide efficient lookup processing to test the underlying table.
• Selection is performed as the bitmap is generated to subset the
number of selected rows in the temporary object.

48 IBM i: Performance and Query Optimization


Table 21. Bitmap probe attributes (continued)
Data access method Bitmap probe attributes
Considerations Since the bitmap contains only the addresses of the selected rows in
the table, a separate Table Probe fetches the table rows.
Likely to be used • When the use of temporary results is allowed by the query
environmental parameter (ALWCPYDTA).
• When the cost of creating and probing the bitmap is justified
by reducing the number of Table Probe operations that must be
performed.
• When multiple indexes over the same table need to be combined in
order to minimize the number of selected rows.

Example SQL statement


CREATE INDEX X1 ON Employee (WorkDept)
CREATE ENCODED VECTOR INDEX EVI2 ON
Employee (Salary)
CREATE ENCODED VECTOR INDEX EVI3 ON
Employee (Job)

SELECT * FROM Employee


WHERE WorkDept = 'E01' AND Job = 'CLERK'
AND Salary = 5000
ORDER BY WorkDept

Database Monitor and Plan QQRID 3001 and QQRID 3021 records for each index used.
Cache record indicating use
The QQC11 field in the 3021 record will be 'BL'.
Optionally, QQRID 3022 records if bitmap merging occurred.

SMP parallel enabled Yes


Also referred to as Bitmap Probe, Preload
Row Number Bitmap Probe
Row Number Bitmap Probe, Preload

Visual Explain icon

Using the example above, the optimizer created a temporary bitmap for each of the encoded vector
indexes. Additionally, an index probe operation was performed against the radix index X1 to satisfy
the ordering requirement. Since the ORDER BY requires that the resulting rows be sequenced by the
WorkDept column, the bitmap cannot be scanned for the selected rows.
However, the temporary bitmap can be probed using a row address extracted from the index X1 used
to satisfy the ordering. By probing the bitmap with the row address extracted from the index probe, the
sequencing of the keys in the index X1 is preserved. The row can still be tested against the selected rows
within the bitmap.

Database performance and query optimization 49


Temporary index
A temporary index is a temporary object that allows the optimizer to create and use a radix index for
a specific query. The temporary index has all the same attributes and benefits as a radix index created
through the CREATE INDEX SQL statement or Create Logical File (CRTLF) CL command.
Additionally, the temporary index is optimized for use by the optimizer to satisfy a specific query request.
This optimization includes setting the logical page size and applying any selection to the index to speed
up its use after creation.
The temporary index can be used to satisfy various query requests:
• Ordering
• Grouping/Distinct
• Joins
• Record selection
Generally a temporary index is a more expensive temporary object to create than other temporary
objects. It can be populated by a table scan, or by one or more index scans or probes. The optimizer
considers all the methods available when determining which method to use to produce the rows for the
index creation. This process is like the costing and selection of the other temporary objects used by the
optimizer.
One significant advantage of the temporary index over other temporary objects is that it is the only
temporary object maintained if the underlying table changes. The temporary index is identical to a radix
index in that any inserts or updates against the table are reflected immediately through normal index
maintenance.
SQE usage of temporary indexes is different from CQE usage in that SQE allows reuse. References to
temporary indexes created and used by the SQE optimizer are kept in the system Plan Cache. A temporary
index is saved for reuse by other instances of the same query or other instances of the same query
running in a different job. It is also saved for potential reuse by a different query that can benefit from the
use of the same temporary index.
By default, an SQE temporary index persists until the Plan Cache entry for the last referencing query
plan is removed. With the SQE Plan Cache auto sizing capability, there is the potential for SQE temporary
indexes to persist longer. You can control this behavior by setting the CACHE_RESULTS QAQQINI value.
The default for this INI value allows the optimizer to keep temporary indexes around for reuse.
Changing the INI value to '*JOB' prevents the temporary index from being saved in the Plan Cache; the
index does not survive a hard close. The *JOB option causes the SQE optimizer use of temporary indexes
to behave more like the CQE optimizer. The temporary index has a shorter life, but is still shared as long
as there are active queries using it. This behavior can be desirable in cases where there is concern about
increased maintenance costs for temporary indexes that persist for reuse.
A SQE temporary index can also be used as a source of statistics.
A temporary index is an internal data structure and can only be created by the database manager.
Visual explain icon:

Temporary index scan


A temporary index scan operation is identical to the index scan operation that is performed upon the
permanent radix index. It is still used to retrieve the rows from a table in a keyed sequence; however, the

50 IBM i: Performance and Query Optimization


temporary index object must first be created. All the rows in the index are sequentially processed, but the
resulting row numbers are sequenced based upon the key columns.
The sequenced rows can be used by the optimizer to satisfy a portion of the query request (such as
ordering or grouping).

Table 22. Temporary index scan attributes


Data access method Temporary index scan
Description Sequentially scan and process all the keys associated with the
temporary index.
Advantages • Potential to extract all the data from the index key values, thus
eliminating the need for a Table Probe
• Returns the rows back in a sequence based upon the keys of the
index

Considerations Generally requires a Table Probe to be performed to extract any


remaining columns required to satisfy the query. Can perform poorly
when many rows are selected because of the random I/O associated
with the Table Probe.
Likely to be used • When sequencing the rows is required for the query (for example,
ordering or grouping)
• When the selection columns cannot be matched against the leading
key columns of the index
• When the overhead cost associated with the creation of the
temporary index can be justified against other alternative methods
to implement this query

Example SQL statement


SELECT * FROM Employee
WHERE WorkDept BETWEEN 'A01' AND 'E01'
ORDER BY LastName
OPTIMIZE FOR ALL ROWS

Database Monitor and Plan QQRID 3002 record and QQRID 3001
Cache record indicating use
where QQKP(Index_Probe_Used) = 'N'.

SMP parallel enabled Yes


Also referred to as Index Scan
Index Scan, Preload
Index Scan, Distinct
Index Scan Distinct, Preload
Index Scan, Key Selection

Visual Explain icon

Database performance and query optimization 51


Using the example above, the optimizer chose to create a temporary index to sequence the rows based
upon the LastName column. A temporary index scan might then be performed to satisfy the ORDER BY
clause in this query.
The optimizer determines where the selection against the WorkDept column best belongs. It can be
performed as the temporary index itself is being created or it can be performed as a part of the temporary
index scan. Adding the selection to the temporary index creation has the possibility of making the
open data path (ODP) for this query non-reusable. This ODP reuse is considered when determining how
selection is performed.

Temporary index probe


A temporary index probe operation is identical to the index probe operation that is performed on the
permanent radix index. Its main function is to provide quick access against the index keys of the
temporary index. However, it can still be used to retrieve the rows from a table in a keyed sequence.
The temporary index is used by the optimizer to satisfy the join portion of the query request.

Table 23. Temporary index probe attributes


Data access method Temporary index probe
Description The index is quickly probed based upon the selection criteria that
were rewritten into a series of ranges. Only those keys that satisfy the
selection is used to generate a table row number.
Advantages • Only those index entries that match any selection continue to be
processed. Provides quick access to the selected rows
• Potential to extract all the data from the index key values, thus
eliminating the need for a Table Probe
• Returns the rows back in a sequence based upon the keys of the
index

Considerations Generally requires a Table Probe to be performed to extract any


remaining columns required to satisfy the query. Can perform poorly
when many rows are selected because of the random I/O associated
with the Table Probe.
Likely to be used • When the ability to probe the rows required for the query (for
example, joins) exists
• When the selection columns cannot be matched against the leading
key columns of the index
• When the overhead cost associated with the creation of the
temporary index can be justified against other alternative methods
to implement this query

Example SQL statement


SELET * FROM Employee XXX, Department YYY
WHERE XXX.WorkDept = YYY.DeptNo
OPTIMIZE FOR ALL ROWS

Database Monitor and Plan QQRID 3002 record and QQRID 3001
Cache record indicating use
where QQKP(Index_Probe_Used) = 'Y'.

SMP parallel enabled Yes

52 IBM i: Performance and Query Optimization


Table 23. Temporary index probe attributes (continued)
Data access method Temporary index probe
Also referred to as Index Probe
Index Probe, Preload
Index Probe, Distinct
Index Probe Distinct, Preload
Index Probe, Key Selection

Visual Explain icon

Using the example above, the optimizer chose to create a temporary index over the DeptNo column to
help satisfy the join requirement against the DEPARTMENT table. A temporary index probe was then
performed against the temporary index to process the join criteria between the two tables. In this
particular case, there was no additional selection that might be applied against the DEPARTMENT table
while the temporary index was being created.

Temporary buffer
The temporary buffer is a temporary object that is used to help facilitate operations such as parallelism.
It is an unsorted data structure that is used to store intermediate rows of a query. The difference between
a temporary buffer and a temporary list is that the buffer does not need to be fully populated before its
results are processed.
The temporary buffer acts as a serialization point between parallel and non-parallel portions of a query.
The operations used to populate the buffer cannot be performed in parallel, whereas the operations that
fetch rows from the buffer can be performed in parallel.
The temporary buffer is required for SQE because the index scan and index probe operations are not SMP
parallel-enabled for this engine. Unlike CQE, which performs these index operations in parallel, SQE does
not subdivide the index operation work to take full advantage of parallel processing.
The buffer is used to allow a query to be processed under parallelism by serializing access to the index
operations. Any remaining work within the query is processed in parallel.
A temporary buffer is an internal data structure and can only be created by the database manager.
Visual explain icon:

Buffer scan
The buffer scan is used when a query is processed using Db2 Symmetric Multiprocessing, yet a portion of
the query is unable to be parallel processed. The buffer scan acts as a gateway to control access to rows
between the parallel enabled portions of the query and the non-parallel portions.
Multiple threads can be used to fetch the selected rows from the buffer, allowing the query to perform any
remaining processing in parallel. However, the buffer is populated in a non-parallel manner.

Database performance and query optimization 53


A buffer scan operation is identical to the list scan operation that is performed upon the temporary list
object. The main difference is that a buffer does not need to be fully populated before the start of the scan
operation. A temporary list requires that the list is fully populated before fetching any rows.

Table 24. Buffer scan attributes


Data access method Buffer scan
Description Sequentially scan and process all the rows in the temporary buffer.
Enables SMP parallelism to be performed over a non-parallel portion of
the query.
Advantages • The temporary buffer can be used to enable parallelism over a
portion of a query that is non-parallel
• The temporary buffer does not need to be fully populated in order to
start fetching rows

Considerations Used to prevent portions of the query from being processed multiple
times when no key columns are required to satisfy the request.
Likely to be used • When the query is attempting to take advantage of Db2 Symmetric
Multiprocessing
• When a portion of the query cannot be performed in parallel (for
example, index scan or index probe)

Example SQL statement


CHGQRYA DEGREE(*OPTIMIZE)
CREATE INDEX X1 ON
Employee (LastName, WorkDept)

SELECT * FROM Employee


WHERE WorkDept BETWEEN 'A01' AND 'E01'
AND LastName IN ('Smith', 'Jones', 'Peterson')
OPTIMIZE FOR ALL ROWS

Database Monitor and Plan QVPARU will be greater than 0 on the associated database monitor
Cache record indicating use record.
SMP parallel enabled Yes
Also referred to as Not applicable
Visual Explain icon

Using the example above, the optimizer chose to use the existing index X1 to perform an index probe
operation against the table. In order to speed up the remaining Table Probe operation for this query, Db2
Symmetric Multiprocessing is used to perform the random probe into the table. Since the index probe is
not SMP parallel-enabled for SQE, it is placed within a temporary buffer to control access to the selected
index entries.

Queue
The Queue is a temporary object that the optimizer uses to feed recursion by putting data values needed
for the recursion on it. This data typically includes those values used on the recursive join predicate, and
other recursive data accumulated or manipulated during the recursive process.
The Queue has two operations allowed:

54 IBM i: Performance and Query Optimization


• Enqueue: puts data on the queue
• Dequeue: takes data off the queue
A queue is an efficient data structure because it contains only the data needed to feed the recursion or
directly modified by the recursion process. Its size is managed by the optimizer.
Unlike other temporary objects created by the optimizer, the queue is not populated all at once by the
underlying query node tree. It is a real-time temporary holding area for values feeding the recursion.
In this regard, a queue is not considered temporary, as it does not prevent the query from running if
ALWCPYDTA(*NO) was specified. The data can flow from the query at the same time the recursive values
are inserted into the queue and used to retrieve additional join rows.
A queue is an internal data structure and can only be created by the database manager.
Visual explain icon:

Enqueue
During an enqueue operation, an entry is put on the queue. The entry contains key values used by the
recursive join predicates or data manipulated as a part of the recursion process. The optimizer always
supplies an enqueue operation to collect the required recursive data on the query node directly above the
Union All.

Table 25. Enqueue Attributes


Data Access Method Enqueue
Description Places an entry on the queue needed to cause further recursion
Advantages • Required as a source for the recursion. Only enqueues required
values for the recursion process. Each entry has short life span, until
it is dequeued.
• Each entry on the queue can seed multiple iterative fullselects that
are recursive from the same RCTE or view.

Likely to be used A required access method for recursive queries


Example SQL statement
WITH RPL (PART, SUBPART, QUANTITY) AS
( SELECT ROOT.PART, ROOT.SUBPART, ROOT.QUANTITY
FROM PARTLIST ROOT
WHERE ROOT.PART = '01'
UNION ALL
SELECT CHILD.PART, CHILD.SUBPART, CHILD.QUANTITY
FROM RPL PARENT, PARTLIST CHILD
WHERE PARENT.SUBPART = CHILD.PART
)
SELECT DISTINCT PART, SUBPART, QUANTITY
FROM RPL

Database Monitor and Plan There are no explicit records that indicate the use of an enqueue
Cache record indicating use
SMP parallel enabled Yes
Also referred to as Not applicable

Database performance and query optimization 55


Table 25. Enqueue Attributes (continued)
Data Access Method Enqueue
Visual Explain icon

Use the CYCLE option in the definition of the recursive query if the data reflecting the parent-child
relationship could be cyclic, causing an infinite recursion loop. CYCLE prevents already visited recursive
key values from being put on the queue again for a given set of related (ancestry chain) rows.
Use the SEARCH option in the definition of the recursive query to return the results of the recursion in
the specified parent-child hierarchical ordering. The search choices are Depth or Breadth first. Depth first
means that all the descendents of each immediate child are returned before the next child is returned.
Breadth first means that each child is returned before their children are returned.
SEARCH requires not only the specification of the relationship keys, the columns which make up the
parent-child relationship, and the search type of Depth or Breadth. It also requires an ORDER BY clause in
the main query on the provided sequence column in order to fully implement the specified ordering.

Dequeue
During a dequeue operation, an entry is taken off the queue. Those values specified by recursive
reference are fed back in to the recursive join process.
The optimizer always supplies a corresponding enqueue, dequeue pair of operations for each recursive
common table expression or recursive view in the specifying query. Recursion ends when there are no
more entries to pull off the queue.

Table 26. Dequeue Attributes


Data Access Method Dequeue
Description Removes an entry off the queue. Minimally, provides one side of
the recursive join predicate that feeds the recursive join and other
data values that are manipulated through the recursive process. The
dequeue operation is always on the left side of the inner join with
constraint, where the right side is the target child rows.
Advantages • Provides quick access to recursive values
• Allows for post selection of local predicate on recursive data values

Likely to be used • A required access method for recursive queries


• A single dequeued value can feed the recursion of multiple iterative
fullselects that reference the same RCTE or view

Example SQL statement


WITH RPL (PART, SUBPART, QUANTITY) AS
( SELECT ROOT.PART, ROOT.SUBPART, ROOT.QUANTITY
FROM PARTLIST ROOT
WHERE ROOT.PART = '01'
UNION ALL
SELECT CHILD.PART, CHILD.SUBPART, CHILD.QUANTITY
FROM RPL PARENT, PARTLIST CHILD
WHERE PARENT.SUBPART = CHILD.PART
)
SELECT DISTINCT PART, SUBPART, QUANTITY
FROM RPL

56 IBM i: Performance and Query Optimization


Table 26. Dequeue Attributes (continued)
Data Access Method Dequeue
Database Monitor and Plan There are no explicit records that indicate the use of the dequeue
Cache record indicating use operation.
SMP parallel enabled Yes
Also referred to as Not applicable
Visual Explain icon

Array unnest temporary table


The array unnest temporary table is a temporary object that holds the output of an UNNEST of an array
or a list of arrays. It can be viewed vertically, with each column of array values having the same format.
The temporary table contains one or more arrays specified by the user in an UNNEST clause of a SELECT
statement.
UNNEST creates a temporary table with the arrays specified as columns in the table. If more than one
array is specified, the first array provides the first column in the result table. The second array provides
the second column, and so on.
The arrays might be of different lengths. Shorter arrays are primed with nulls to match the length of the
longest array in the list.
If WITH ORDINALITY is specified, an extra counter column of type BIGINT is appended to the temporary
table. The ordinality column contains the index position of the elements in the arrays.
The array unnest temporary table is an internal data structure and can only be created by the database
manager.

Visual explain icon:


Related reference
QAQQINI query options
There are different options available for parameters in the QAQQINI file.
Related information
Array support in SQL procedures
Debugging an SQL routine
table-reference

Database performance and query optimization 57


Array unnest temporary table scan
During an array unnest temporary table scan operation, the temporary table is processed one row at a
time.

Table 27. Array unnest temporary table scan operation


Data access method Array unnest temporary table scan
Description Sequentially scan and process all the rows of data in the unnest
temporary table.
Advantages The array unnest temporary table and temporary table scan can be
used to simplify the logic flow of the optimizer for processing arrays.
Likely to be used When an UNNEST clause is specified in the from-clause of an SQL
fullselect.
Example SQL statement
CREATE PROCEDURE processCustomers()
BEGIN
DECLARE ids INTARRAY;
DECLARE names STRINGARRAY;
set ids = ARRAY[5,6,7];
set names = ARRAY['Ann', 'Bob', 'Sue'];
INSERT INTO customerTable(id, name, order)
(SELECT Customers.id, Customers.name, Customers.order
FROM UNNEST(ids, names) WITH ORDINALITY
AS Customers(id, name, order) );
END

CALL processCustomers()

Database Monitor and Plan QQRID 3000 where QVQTBL = '*UNNEST'


Cache record indicating use
SMP parallel enabled Yes
Also referred to as
Visual Explain icon

Temporary Indexed List


The temporary indexed list is a temporary object that allows the optimizer to sequence rows based upon a
column or set of columns. The temporary indexed list can be scanned by the optimizer to satisfy ordering
or grouping requirements of the query.
A temporary indexed list is a data structure that contains a radix index object to provide ordering. This
object is generally used when a query contains ordering and non-equal predicates and only a partial
answer set is fetched. The object is initially populated with a distinct set of values by distinct scanning
or probing an existing index. As processing continues and more rows are needed, additional rows will be
inserted into the temporary indexed list for additional processing.
If the underlying index used to build the temporary indexed list contains all the necessary columns
to satisfy any further processing, then these columns are built into the temporary indexed list. This
population avoids any random I/Os associated with a table probe operation. If the underlying index does
not contain all the necessary columns, then a table probe operation is required to recollect the missing
columns from the temporary indexed list before the selected rows can be processed.

58 IBM i: Performance and Query Optimization


A temporary indexed list is an internal data structure and can only be created by the database manager.
The temporary indexed list is always used in conjunction with the temporary indexed list scan and index
merge data access methods.
Visual explain icon:

Temporary Indexed List scan and Index Merge


A temporary indexed list scan operation is similar to the index scan operation that is performed upon the
permanent radix index. It is still used to retrieve the rows from a table in a keyed sequence; however, the
temporary indexed list object must first be created. This operation is often performed in conjunction with
an index merge operation. However, for some distinct and grouping queries, the temporary indexed list
scan may be used without an associated index merge operation.
This access method is used when there is non-equal selection and is used in conjunction with an existing
permanent radix index. A distinct index scan or a distinct index probe operation is performed against the
index to get a unique set of rows. The rows are then inserted into the temporary indexed list to provide the
appropriate ordering.
In general, for a radix index to be eligible for temporary list scan and Index Merge Ordering, the index
should be created as follows:
• Any columns with equal predicates that are not in the ORDER BY list should be first keys in the index.
• Followed by any columns for non-equal predicates that are not in the ORDER BY list. The columns
should be arranged so the most selective predicate column is the first column following the equal
predicate columns.
• Followed by the ORDER BY columns in the same order as the ORDER BY clause of the query and with
the same ASC or DESC attribute.
• Optionally, at the end you may include other selection columns or other selected columns for Index
Only Access.
A temporary sorted list is an internal data structure and can only be created by the database manager.

Table 28. Temporary indexed list scan


Data access method Temporary indexed list scan
Description Sequentially scan and process all the keys
associated with the temporary indexed list.
Advantages • Provides an alternate implementation to order
data when the query contains non-equal where
selection.
• Returns the rows back in a sequence based upon
the keys of the index.
• Provides better paging characteristics than a
sorted list scan in low memory environments.
• Provides better performance characteristics than
a Sorted List Scan when only a partial answer set
is fetched.

Considerations Used to process ordering, grouping or distinct


processing for a single table query.

Database performance and query optimization 59


Table 28. Temporary indexed list scan (continued)
Data access method Temporary indexed list scan
Likely to be used • When the use of temporary results is
allowed by the query environmental parameter
(ALWCPYDTA).
• When the data is required to be ordered or
grouped based upon a column or columns and
the query contains non-equal where selection.
• The query is being optimized for FIRST I/O.
• • The number of distinct values is low.

Example SQL statement


CREATE INDEX INDEX1 ON EMPLOYEE(SALARY,
WORKDEPT)

SELECT DISTINCT WORKDEPT FROM EMPLOYEE


WHERE SALARY > 30000
OPTIMIZE FOR 30 ROWS

Database Monitor and Plan Cache record QQRID 3001 where QQRCOD = ‘I7’
indicating use
SMP parallel enabled No
Also referred to as
Visual Explain icon

Using the example above, the optimizer chose to create a temporary indexed list of distinct WORKDEPT
values from index INDEX1. The selection SALARY > 3000 was applied to the index probe distinct.

Index Merge:
An index merge operation is used to provide ordering in conjunction with a temporary indexed list scan
and an index probe distinct or distinct index.
The sequenced rows can be used by the optimizer to satisfy a portion of the query request (such as
ordering or grouping).

Table 29. Index Merge


Data access method Index Merge
Description Sequentially scan and process all the keys
associated with the temporary indexed list.
Advantages • Potential to extract all the data from the index
key values, thus eliminating the need for a Table
Probe.
• Returns the rows back in a sequence based upon
the keys of the index.

60 IBM i: Performance and Query Optimization


Table 29. Index Merge (continued)
Data access method Index Merge
Considerations Used to process ordering, grouping or distinct
processing for a single table query.
Likely to be used • When the use of temporary results is
allowed by the query environmental parameter
(ALWCPYDTA).
• When the data is required to be ordered or
grouped based upon a column or columns and
the query contains non-equal where selection.
• The query is being optimized for FIRST I/O.
• The number of distinct values is low.

Example SQL statement


CREATE INDEX IX1 ON
Sales(Sales_date, Region, Sales_person)

SELECT * FROM Sales


WHERE
Sales_date BETWEEN '1996-03-29'
AND '1996-04-29'
AND Region IN ('Quebec','Manitoba')
ORDER BY Sales_person;

Database Monitor and Plan Cache record QQRID 3001 where QQRCOD = ‘I7’
indicating use
SMP parallel enabled No
Also referred to as
Visual Explain icon

Window
The window is a temporary object that holds intermediate results needed to determine the result for
On-Line Analytical Processing (OLAP) functions. The number of rows in the window may change as the
data flows through it.
The window is an internal data structure and can only be created by the database manager.
Visual explain icon:

Database performance and query optimization 61


Window scan
During processing of an OLAP function the window may be processed multiple time in order to determine
the result of the OLAP function for each row

Table 30. Window scan attributes


Data access method Window scan
Description Sequentially scan and process all the rows needed to determine the
result of the OLAP function.
Advantages • Allows the database manager to process subsets of the data to
calculate the OLAP result without processing the entire result set
for each row.

Considerations Required for OLAP specifications that require intermediate results to


determine the value of the OLAP expression. The OLAP specifications
that require a window include any of the aggregate OLAPs, LAG, LEAD,
NTILE, and CUME_DIST.
Likely to be used Required for OLAP specifications that require intermediate results to
determine the value of the OLAP expression.
Example SQL statement
SELECT workdept, empno, salary, decimal(avg(salary)
over(partition by workdept order by salary), 10,2)
FROM employee

Database Monitor and Plan QQRID 3004 where QQRCOD = ‘H8’.


Cache record indicating use
SMP parallel enabled No
Also referred to as
Visual Explain icon

Objects processed in parallel


The Db2 Symmetric multiprocessing feature provides the optimizer with additional methods for retrieving
data that include parallel processing. Symmetrical multiprocessing is a form of parallelism achieved on
a single system where multiple CPU and I/O processors sharing memory and disk work simultaneously
toward a single result.
This parallel processing means that the database manager can have more than one (or all) of the system
processors working on a single query simultaneously. The performance of a CPU-bound query can be
improved with this feature on multiple-processor systems by distributing the processor load across more
than one processor.
The preceding tables indicate what data access methods are enabled to take advantage of the
Db2 Symmetric Multiprocessing feature. An important thing to note, however, is that the parallel
implementation differs for both the SQL Query Engine and the Classic Query Engine.

Processing requirements
Parallelism requires that SMP parallel processing must be enabled by one of the following methods:
• System value QQRYDEGREE

62 IBM i: Performance and Query Optimization


• Query option file
• DEGREE parameter on the Change Query Attributes (CHGQRYA) command
• SQL SET CURRENT DEGREE statement
Once parallelism has been enabled, a set of database system tasks or threads is created at system
startup for use by the database manager. The database manager uses the tasks to process and retrieve
data from different disk devices. Since these tasks can be run on multiple processors simultaneously,
the elapsed time of a query can be reduced. Even though the tasks do much of the parallel I/O and CPU
processing, the I/O and CPU resource accounting is transferred to the application job. The summarized
I/O and CPU resources for this type of application continue to be accurately displayed by the Work with
Active Jobs (WRKACTJOB) command.
The job must be run in a shared storage pool with the *CALC paging option, as this method causes more
efficient use of active memory.
Related concepts
Nested loop join implementation
Db2 for i provides a nested loop join method. For this method, the processing of the tables in the join
are ordered. This order is called the join order. The first table in the final join order is called the primary
table. The other tables are called secondary tables. Each join table position is called a dial.
Related reference
Changing the attributes of your queries
You can modify different types of query attributes for a job with the Change Query Attributes
(CHGQRYA) CL command. You can also use the System i Navigator Change Query Attributes interface.
Related information
SET CURRENT DEGREE statement
Performance system values: Parallel processing for queries and indexes
Adjusting performance automatically
Work with Active Jobs (WRKACTJOB) command
Change Query Attributes (CHGQRYA) command
DB2 Symmetric Multiprocessing

Spreading data automatically


Db2 for i automatically spreads the data across the disk devices available in the auxiliary storage pool
(ASP) where the data is allocated. This process ensures that the data is spread without user intervention.
The spreading allows the database manager to easily process the blocks of rows on different disk
devices in parallel. Even though Db2 for i spreads data across disk devices within an ASP, sometimes
the allocation of the data extents (contiguous sets of data) might not be spread evenly. This unevenness
occurs when there is uneven allocation of space on the devices, or when a new device is added to the ASP.
The allocation of the table data space could be spread again by saving, deleting, and then restoring the
table.
Maintaining an even distribution of data across all the disk devices can lead to better throughput on query
processing. The number of disk devices used and how the data is spread across them is considered by the
optimizer while costing the different plan permutations.

Processing queries: Overview


This overview of the query optimizer provides guidelines for designing queries that perform and use
system resources more efficiently.
This overview covers queries that are optimized by the query optimizer and includes interfaces such as
SQL, OPNQRYF, APIs (QQQQRY), ODBC, and Query/400 queries. Whether you apply the guidelines, the
query results are still correct.

Database performance and query optimization 63


Note: The information in this overview is complex. You might find it helpful to experiment with an IBM i
product as you read this information to gain a better understanding of the concepts.
When you understand how Db2 for i processes queries, it is easier to understand the performance
impacts of the guidelines discussed in this overview. There are two major components of Db2 for i query
processing:
• How the system accesses data.
These methods are the algorithms that are used to retrieve data from the disk. The methods include
index usage and row selection techniques. In addition, parallel access methods are available with the
Db2 Symmetric Multiprocessing operating system feature.
• Query optimizer
The query optimizer identifies the valid techniques which can be used to implement the query and
selects the most efficient technique.

How the query optimizer makes your queries more efficient


Data manipulation statements such as SELECT specify only what data the user wants, not how to retrieve
that data. This path to the data is chosen by the optimizer and stored in the access plan. Understand the
techniques employed by the query optimizer for performing this task.
The optimizer is an important part of Db2 for i because the optimizer:
• Makes the key decisions which affect database performance.
• Identifies the techniques which can be used to implement the query.
• Selects the most efficient technique.

General query optimization tips


Here are some tips to help your queries run as fast as possible.
• Create indexes whose leftmost key columns match your selection predicates to help supply the
optimizer with selectivity values (key range estimates).
• For join queries, create indexes that match your join columns to help the optimizer determine the
average number of matching rows.
• Minimize extraneous mapping by specifying only columns of interest on the query. For example, specify
only the columns you need to query on the SQL SELECT statement instead of specifying SELECT *. Also,
specify FOR FETCH ONLY if the columns do not need to be updated.
• If your queries often use table scan, use the Reorganize Physical File Member (RGZPFM)
command to remove deleted rows from tables, or the Change Physical File (CHGPF) REUSEDLT
(*YES) command to reuse deleted rows.
Consider using the following options:
• Specify ALWCPYDTA(*OPTIMIZE) to allow the query optimizer to create temporary copies of data so
better performance can be obtained. The IBM i Access ODBC driver and Query Management driver
always use this mode. If ALWCPYDTA(*YES) is specified, the query optimizer attempts to implement the
query without copies of the data, but might create copies if required. If ALWCPYDTA(*NO) is specified,
copies of the data are not allowed. If the query optimizer cannot find a plan that does not use a
temporary, then the query cannot be run.
• For SQL, use CLOSQLCSR(*ENDJOB) or CLOSQLCSR(*ENDACTGRP) to allow open data paths to remain
open for future invocations.
• Specify DLYPRP(*YES) to delay SQL statement validation until an OPEN, EXECUTE, or DESCRIBE
statement is run. This option improves performance by eliminating redundant validation.
• Use ALWBLK(*ALLREAD) to allow row blocking for read-only cursors.
Related information
Reorganize Physical File Member (RGZPFM) command

64 IBM i: Performance and Query Optimization


Change Physical File (CHGPF) command

Access plan validation


An access plan is a control structure that describes the actions necessary to satisfy each query request.
It contains information about the data and how to extract it. For any query, whenever optimization occurs,
the query optimizer develops an optimized plan of how to access the requested data.
To improve performance, an access plan is saved once it is built (see following exceptions), to be available
for potentially future runs of the query. However, the optimizer has dynamic replan capability. This means
that even if a previously built (and saved) plan is found, the optimizer could rebuild it if a more optimal
plan is possible. This process allows for maximum flexibility while still taking advantage of saved plans.
• For dynamic SQL, an access plan is created at prepare or open time. However, optimization uses the
host variable values to determine an optimal plan. Therefore, a plan built at prepare time could be
rebuilt the first time the query is opened (when the host variable values are present).
• For an IBM i program that contains static embedded SQL, an access plan is initially created at compile
time. Again, since optimization uses the host variable values to determine an optimal plan, the compile-
time plan could be rebuilt the first time the query is opened.
• For Open Query File (OPNQRYF), an access plan is created but is not saved. A new access plan is
created each time the OPNQRYF command is processed.
• For Query/400, an access plan is saved as part of the query definition object.
In all the preceding cases where a plan is saved, including static SQL, dynamic replan can still apply as
the queries are run over time.
The access plan is validated when the query is opened. Validation includes the following:
• Verifying that the same tables are referenced in the query as in the access plan. For example, the tables
were not deleted and recreated or that the tables resolved by using *LIBL have not changed.
• Verifying that the indexes used to implement the query, still exist.
• Verifying that the table size or predicate selectivity has not changed significantly.
• Verifying that QAQQINI options have not changed.

Single table optimization


At run time, the optimizer chooses an optimal access method for a query by calculating an implementation
cost based on the current state of the database. The optimizer uses two costs in its decision: an I/O cost
and a CPU cost. The goal of the optimizer is to minimize both I/O and CPU cost.

Improved query optimization I/O cost estimates


The time it takes to perform an disk I/O operation can vary according to the connecting infrastructure, the
external or internal nature of the media and media type, spinning disk or Solid State Disk. Consequently,
the total I/O cost associated with a particular query access method may vary from system to system.
In order to more accurately estimate these costs, the optimizer considers the performance of each disk
unit individually. It does this by measuring the time it takes for read operations to complete across a
sample of pages across the disk. This analysis is done at each IPL for disks in the system and user ASPs
and at vary-on time for independent ASPs. With this information and with the additional knowledge about
how database objects are spread across various disk units, the optimizer can make a reasonable estimate
about the time it takes to perform I/O against a given database object. This means that no matter where
your data resides, and even as it moves around, the optimizer can choose the most efficient plan to
execute your queries.

Optimizing Access to each table


The optimizer uses a general set of guidelines to choose the best method for accessing data in each table.
The optimizer:

Database performance and query optimization 65


• Determines the default filter factor for each predicate in the selection clause.
• Determines the true filter factor of the predicates by key range estimate when the selection predicates
match the index left-most keys, or by available column statistics.
• Determines the cost of table scan processing if an index is not required.
• Determines the cost of creating an index over a table if an index is required. This index is created by
performing either a table scan or creating an index-from-index.
• Determines the cost of using a sort routine or hashing method if appropriate.
• Determines the cost of using existing indexes using Index Probe or Index Scan
– Orders the indexes. For SQE, the indexes are ordered in general such that the indexes that access the
smallest number of entries are examined first. For CQE, the indexes are ordered from mostly recently
created to oldest.
– For each index available, the optimizer does the following:
- Determines if the index meets the selection criteria.
- Determines the cost of using the index by estimating the number of I/Os and CPU needed to Index
Probe or Index Scan, and possible Table Probes.
- Compares the cost of using this index with the previous cost (current best).
- Picks the cheaper one.
- Continues to search for best index until the optimizer decides to look at no more indexes.
SQE orders the indexes so that the best indexes are examined first. Once an index is found that is
more expensive than the previously chosen best index, the search is ended.
For CQE, the time limit controls how much time the optimizer spends choosing an implementation.
The time limit is based on how much time was spent so far and the current best implementation
cost found. The idea is to prevent the optimizer from spending more time optimizing the query
than it takes to actually execute the query. Dynamic SQL queries are subject to the optimizer
time restrictions. Static SQL query optimization time is not limited. For OPNQRYF, if you specify
OPTALLAP(*YES), the optimization time is not limited.
For small tables, the query optimizer spends little time in query optimization. For large tables,
the query optimizer considers more indexes. For CQE, the optimizer generally considers five or six
indexes for each table of a join before running out of optimization time. Because of this processing, it
is normal for the optimizer to spend longer lengths of time analyzing queries against the tables.
• Determines the cost of using a temporary bitmap
– Order the indexes that can be used for bit mapping. In general the indexes that select the smallest
number of entries are examined first.
– Determine the cost of using this index for bit mapping and the cost of merging this bitmap with any
previously generated bitmaps.
– If the cost of this bitmap plan is cheaper than the previous bitmap plan, continue searching for
bitmap plans.
• After examining the possible methods of access the data for the table, the optimizer chooses the best
plan from all the plans examined.

Solid State Drives


Solid State Drives (SSDs) offer a number of advantages over traditional hard disk drives (HDDs)

Solid State Drives


Solid State Drives (SSDs) offer a number of advantages over traditional hard disk drives (HDDs). With no
seek time or rotational delays, SSDs can deliver substantially better I/O performance than HDDs. Capable
of driving tens of thousands of I/O operations per second as opposed to hundreds for HDDs, SSDs break
through performance bottlenecks of I/O-bound applications. Applications that require dozens and dozens

66 IBM i: Performance and Query Optimization


of “extra” HDDs for performance can meet their I/O performance requirements with far fewer SSDs,
resulting in energy, space, and cost savings.
As IBM i has it’s own storage manager and Db2 for i built in, the integration of SSDs on IBM i is a fairly
simple task. The functions provided for management of SSDs and adjusting their impact on Applications
and Database are very simple and easy to use.
There are three basic methodologies to place data on SSD.
• ASP Balancer – Enhanced for SSDs
• Library and SSD Integration
• Db2 and SSD Integration
To allow you to specify what data should be allocated on SSD, Db2 has provided the capability to specify
a “media preference” as an attribute of a database table, partition, or index. It should be noted that this
attribute specifies that storage allocations on SSD are preferred, but if no SSD disks are available or if the
SSD disks do not have enough space left to allocate the entire object, at least some part of the object will
be allocated on traditional disks. See the UNIT parameter on CRTPF and CRTLF or the UNIT clause on the
CREATE TABLE, CREATE INDEX and ALTER TABLE SQL statements.
You should consider SSDs if your I/O demands have outpaced the performance capabilities of traditional
HDDs, latencies associated with spinning platters and moving arms limit the speed of HDD data access.
SSDs’ near instantaneous data access removes this I/O bottleneck, creating a paradigm shift in I/O
performance. Applications throttled by poor I/O performance can benefit greatly from SSDs.

Memory preference controls


Memory preference controls can be used as a technique to maximize performance and utilization of
resources.

Memory preference controls


Memory preference controls can be used against performance critical database tables, indexes, physical
files, and logical files as a technique to maximize performance and utilization of resources. Several
approaches are available for controlling the memory preference:
1. Set Object Access (SETOBJACC) command
One benefit of SETOBJACC is that you can carve out a separate memory pool that is not used by from
any running applications or MEMORY_POOL_PREFERENCE and those objects will then not get paged
out because neither applications nor SQE will be using that pool. If the target objects are primarily
accessed using Native database I/O,SETOBJACC is the preferred approach.SETOBJACC uses a single
thread to bring the object into memory.
2. Change Physical File (CHGPF) and Change Logical File (CHGLF) commands - Keep in
memory (KEEPINMEM) parameter
When an object is changed to have Keep in memory set to *YES, the database will bring the object into
memory and attempt to keep it in memory when it is accessed using SQL via SQE. Native database I/O
(for example RPG CHAIN, READ, etc.) does not do this.KEEPINMEM has the ability to use parallel I/O to
bring the object into memory.
• CHGPF KEEPINMEM(*YES|*NO)
• CHGLF KEEPINMEM(*YES|*NO)
3. The SQL memory-preference can be used as an alternative to the KEEPINMEM command parameter.
The behavior of SQL configured in memory objects matches the behavior described in theKEEPINMEM
section.
KEEP IN MEMORY <NO/YES> is available on the following SQL statements:
• ALTER TABLE
• CREATE INDEX

Database performance and query optimization 67


• CREATE TABLE
• DECLARE GLOBAL TEMPORARY TABLE
Note: The QSYS2/SYSPARTITIONSTAT and SYSPARTITIONINDEXSTAT catalogs can be queried to
determine the memory-preference for specific objects. When a memory-preference is specified for an
object, the MEMORY_POOL_PREFERENCE QAQQINI option can be used to influence where we attempt to
page objects. There is no guarantee that objects will remain in memory.

Join optimization
A join operation is a complex function that requires special attention in order to achieve good
performance. This section describes how Db2 for i implements join queries and how optimization choices
are made by the query optimizer. It also describes design tips and techniques which help avoid or solve
performance problems.

Nested loop join implementation


Db2 for i provides a nested loop join method. For this method, the processing of the tables in the join
are ordered. This order is called the join order. The first table in the final join order is called the primary
table. The other tables are called secondary tables. Each join table position is called a dial.
The nested loop is implemented either using an index on secondary tables, a hash table, or a table scan
(arrival sequence) on the secondary tables. In general, the join is implemented using either an index or a
hash table.

Index nested loop join implementation


During the join, Db2 for i:
1. Accesses the first primary table row selected by the predicates local to the primary table.
2. Builds a key value from the join columns in the primary table.
3. Chooses the access to the first secondary table:
• If using an index, Radix Index Probe is used to locate the first row satisfying the join condition for
the secondary table. The probe uses an index with keys matching the join condition or local row
selection columns of the secondary table.
• Applies bitmap selection, if applicable.
All rows that satisfy the join condition from each secondary dial are located using an index. Rows
are retrieved from secondary tables in random sequence. This random disk I/O time often accounts
for a large percentage of the processing time of the query. Since a given secondary dial is searched
once for each row selected from the primary and the preceding secondary dials that satisfy the join
condition for each of the preceding secondary dials, many searches could be against the later dials.
Any inefficiencies in the processing of the later dials can significantly inflate the query processing
time. This reason is why attention to performance considerations for join queries can reduce the run
time of a join query from hours to minutes.
If an efficient index cannot be found, a temporary index could be created. Some join queries build
temporary indexes over secondary dials even when an index exists for all the join keys. Because
efficiency is important for secondary dials of longer running queries, the optimizer could build a
temporary index containing only entries with local row selection for that dial. This preprocessing of
row selection allows the database manager to process row selection in one pass instead of each time
rows are matched for a dial.
• If using a Hash Table Probe, a hash temporary result table is created containing all rows from local
selection against the table on the first probe. The structure of the hash table is such that rows with
the same join value are loaded into the same hash table partition (clustered). The location of the
rows for any given join value can be found by applying a hashing function to the join value.
A nested loop join using a Hash Table Probe has several advantages over a nested loop join using an
Index Probe:

68 IBM i: Performance and Query Optimization


– The structure of a hash temporary result table is simpler than the structure of an index. Less CPU
processing is required to build and probe a hash table.
– The rows in the hash result table contain all the data required by the query. There is no need to
access the dataspace of the table with random I/O when probing the hash table.
– Like join values are clustered, so all matching rows for a given join value can typically be accessed
with a single I/O request.
– The hash temporary result table can be built using SMP parallelism.
– Unlike indexes, entries in hash tables are not updated to reflect changes of column values in
the underlying table. The existence of a hash table does not affect the processing cost of other
updating jobs in the system.
• If using a Sorted List Probe, a sorted list result is created containing all the rows from local selection
against the table on the first probe. The structure of the sorted list table is such that rows with the
same join value are sorted together in the list. The location of the rows for any given join value can be
found by probing using the join value.
• If using a Table Scan, locate the first row that satisfies the join condition or local row selection
columns of the secondary table. The join could be implemented with a table scan when the
secondary table is a user-defined table function.
4. Determines if the row is selected by applying any remaining selection local to the first secondary dial.
If the secondary dial row is not selected then the next row that satisfies the join condition is located.
Steps 1 through 4 are repeated until a row that satisfies both the join condition and any remaining
selection is selected from all secondary tables
5. Returns the result join row.
6. Processes the last secondary table again to find the next row that satisfies the join condition in that
dial.
During this processing, when no more rows satisfying the join condition can be selected, the
processing backs up to the logical previous dial. It attempts to read the next row that satisfies its
join condition.
7. Ends processing when all selected rows from the primary table are processed.
Note the following characteristics of a nested loop join:
• If ordering or grouping is specified, and all the columns are over a single table eligible to be the primary,
then the optimizer costs the join with that table as the primary table, performing the grouping and
ordering with an index.
• If ordering and grouping is specified on two or more tables or if temporary objects are allowed, Db2 for i
breaks the processing of the query into two parts:
1. Perform the join selection, omitting the ordering or grouping processing, and write the result rows to
a temporary work table. This method allows the optimizer to consider any table of the join query as a
candidate for the primary table.
2. Perform the ordering or grouping on the data in the temporary work table.

Queries that cannot use hash join


Hash join cannot be used for queries that:
• Hash join cannot be used for queries involving physical files or tables that have read triggers.
• Require that the cursor position is restored as the result of the SQL ROLLBACK HOLD statement or the
ROLLBACK CL command. For SQL applications using commitment control level other than *NONE, this
method requires that *ALLREAD be specified as the value for the ALWBLK precompiler parameter.
• Hash join cannot be used for a table in a join query where the join condition something other than an
equals operator.
• CQE does not support hash join if the query contains any of the following:

Database performance and query optimization 69


– Subqueries unless all subqueries in the query can be transformed to inner joins.
– UNION or UNION ALL
– Perform left outer or exception join.
– Use a DDS created join logical file.
Related concepts
Objects processed in parallel
The Db2 Symmetric multiprocessing feature provides the optimizer with additional methods for retrieving
data that include parallel processing. Symmetrical multiprocessing is a form of parallelism achieved on
a single system where multiple CPU and I/O processors sharing memory and disk work simultaneously
toward a single result.
Related reference
Table scan
A table scan is the easiest and simplest operation that can be performed against a table. It sequentially
processes all the rows in the table to determine if they satisfy the selection criteria specified in the query.
It does this processing in a way to maximize the I/O throughput for the table.
Sorted list probe
A sorted list probe operation is used to retrieve rows from a temporary sorted list based upon a probe
lookup operation.
Hash table probe
A hash table probe operation is used to retrieve rows from a temporary hash table based upon a probe
lookup operation.
Radix index probe
A radix index probe operation is used to retrieve the rows from a table in a keyed sequence. The main
difference between the radix index probe and the scan is that the rows returned are first identified by a
probe operation to subset them.

Join optimization algorithm


The query optimizer must determine the join columns, join operators, local row selection, dial
implementation, and dial ordering for a join query.
The join columns and join operators depend on the following situations:
• Join column specifications of the query
• Join order
• Interaction of join columns with other row selection
Join specifications not implemented for the dial are deferred until a later dial or, if an inner join, processed
as row selection.
For a given dial, the only join specifications which are usable as join columns are those being joined to
a previous dial. For example, the second dial can only use join specifications which reference columns in
the primary dial. Likewise, the third dial can only use join specifications which reference columns in the
primary and the second dials, and so on. Join specifications which reference later dials are deferred until
the referenced dial is processed.
Note: For OPNQRYF, only one type of join operator is allowed for either a left outer or an exception join.
That is, the join operator for all join conditions must be the same.
When looking for an existing index to access a secondary dial, the query optimizer looks at the left-most
key columns of the index. For a given dial and index, the join specifications which use the left-most key
columns can be used. For example:

DECLARE BROWSE2 CURSOR FOR


SELECT * FROM EMPLOYEE, EMP_ACT
WHERE EMPLOYEE.EMPNO = EMP_ACT.EMPNO
AND EMPLOYEE.HIREDATE = EMP_ACT.EMSTDATE
OPTIMIZE FOR 99999 ROWS

70 IBM i: Performance and Query Optimization


For the index over EMP_ACT with key columns EMPNO, PROJNO, and EMSTDATE, the join operation is
performed only on column EMPNO. After the join is performed, index scan-key selection is done using
column EMSTDATE.
The query optimizer also uses local row selection when choosing the best use of the index for the
secondary dial. If the previous example had been expressed with a local predicate as:

DECLARE BROWSE2 CURSOR FOR


SELECT * FROM EMPLOYEE, EMP_ACT
WHERE EMPLOYEE.EMPNO = EMP_ACT.EMPNO
AND EMPLOYEE.HIREDATE = EMP_ACT.EMSTDATE
AND EMP_ACT.PROJNO = '123456'
OPTIMIZE FOR 99999 ROWS

The index with key columns EMPNO, PROJNO, and EMSTDATE are fully utilized by combining join and
selection into one operation against all three key columns.
When creating a temporary index, the left-most key columns are the usable join columns in that dial
position. All local row selection for that dial is processed when selecting entries for inclusion into the
temporary index. A temporary index is like the index created for a select/omit keyed logical file. The
temporary index for the previous example has key columns of EMPNO and EMSTDATE.
Since the optimizer tries a combination of join and local row selection, you can achieve almost all the
advantages of a temporary index by using an existing index. In the preceding example, using either
implementation, an existing index could be used or a temporary index could be created. A temporary
index is built with the local row selection on PROJNO applied during the index creation. The temporary
index has key columns of EMPNO and EMSTDATE to match the join selection.
If, instead, an existing index was used with key columns of EMPNO, PROJNO, EMSTDATE (or PROJNO,
EMP_ACT, EMSTDATE), the local row selection can be applied at the same time as the join selection.
This method contrasts to applying the local selection before the join selection, as happens when the
temporary index is created. Or applying the local selection after the join selection, as happens when only
the first key column of the index matches the join column.
The existing index implementation is more likely to provide faster performance because join and selection
processing are combined without the overhead of building a temporary index. However, the existing index
could have slightly slower I/O processing than the temporary index because the local selection is run
many times rather than once. In general, create indexes with key columns for the combination of join and
equal selection columns as the left-most keys.

Join order optimization


The SQE optimizer allows join reordering for a join logical file. However, the join order is fixed if
CQE runs a query that references a join logical file. The join order is also fixed if the OPNQRYF
JORDER(*FILE) parameter is specified. In addition, the join order is fixed if the query options file
(QAQQINI) FORCE_JOIN_ORDER parameter is *YES
Otherwise, the following join ordering algorithm is used to determine the order of the tables:
1. Determine an access method for each individual table as candidates for the primary dial.
2. Estimate the number of rows returned for each table based on local row selection.
If the join query with ordering or grouping is processed in one step, the table with the ordering or
grouping columns is the primary table.
3. Determine an access method, cost, and expected number of rows returned for each join combination
of candidate tables as primary and first secondary tables.
The join order combinations estimated for a four table inner join would be:

1-2 2-1 1-3 3-1 1-4 4-1 2-3 3-2 2-4 4-2 3-4 4-3

4. Choose the combination with the lowest join cost and number of selected rows or both.
5. Determine the cost, access method, and expected number of rows for each remaining table joined to
the previous secondary table.

Database performance and query optimization 71


6. Select an access method for each table that has the lowest cost for that table.
7. Choose the secondary table with the lowest join cost and number of selected rows or both.
8. Repeat steps 4 through 7 until the lowest cost join order is determined.
Note: After dial 32, the optimizer uses a different method to determine file join order, which might not be
the lowest cost.
When a query contains a left or right outer join or a right exception join, the join order is not fixed.
However, all from-columns of the ON clause must occur from dials previous to the left or right outer or
exception join. For example:

FROM A INNER JOIN B ON A.C1=B.C1


LEFT OUTER JOIN C ON B. C2=C.C2

The allowable join order combinations for this query would be:
1–2–3, 2–1–3, or 2–3–1
Right outer or right exception joins are implemented as left outer and left exception, with files flipped. For
example:

FROM A RIGHT OUTER JOIN B ON A.C1=B.C1

is implemented as B LEFT OUTER JOIN A ON B.C1=A.C1. The only allowed join order is 2–1.
Related information
Open Query File (OPNQRYF) command
Change Query Attributes (CHGQRYA) command

Full outer join


Full outer join is supported by the SQE optimizer. Just as right outer and right exception join are rewritten
to the supported join types of inner, left outer or left exception, a full outer join is also rewritten.
A full outer join of A FULL OUTER JOIN B is equivalent to a (A LEFT OUTER JOIN B) UNION ALL (B LEFT
EXCEPTION JOIN A). The following example illustrates the rewrite.

SELECT EMPNO, LASTNAME, DEPTNAME


FROM CORPDATA.EMPLOYEE XXX
FULL OUTER JOIN CORPDATA.DEPARTMENT YYY
ON XXX.WORKDEPT = YYY.DEPTNO

This query is rewritten as the following:

SELECT EMPNO, LASTNAME, DEPTNAME


FROM CORPDATA.EMPLOYEE XXX
LEFT OUTER JOIN CORPDATA.DEPARTMENT YYY
ON XXX.WORKDEPT = YYY.DEPTNO
UNION ALL
SELECT EMPNO, LASTNAME, DEPTNAME
FROM CORPDATA.DEPARTMENT YYY
LEFT EXCEPTION JOIN CORPDATA.EMPLOYEE XXX
ON XXX.WORKDEPT = YYY.DEPTNO

A query with multiple FULL OUTER JOIN requests, such as A FULL OUTER JOIN B FULL OUTER JOIN
C can quickly become complicated in this rewritten state. This complication is illustrated in the following
example.
If not running in live data mode, the optimizer could facilitate performance both during optimization and
runtime by encapsulating intermediate results in a temporary data object. This object can be optimized
once and plugged into both the scanned and probed side of the rewrite. These shared temporary objects
eliminate the need to make multiple passes through the specific tables to satisfy the request.
In this example, the result of the (A FULL OUTER JOIN B) is a candidate for encapsulation during its FULL
OUTER join with C.

72 IBM i: Performance and Query Optimization


A FULL OUTER JOIN B FULL OUTER JOIN C

This query is rewritten as the following:

((A LEFT OUTER JOIN B) UNION ALL (B LEFT EXCEPTION JOIN A)) LEFT OUTER JOIN C )
UNION ALL
(C LEFT EXCEPTION JOIN ((A LEFT OUTER JOIN B) UNION ALL (B LEFT EXCEPTION JOIN A))

FULL OUTER implies that both sides of the join request can generate NULL values in the resulting answer
set. Local selection in the WHERE clause of the query could result in the appropriate downgrade of the
FULL OUTER to a LEFT OUTER or INNER JOIN.
If you want FULL OUTER JOIN behavior and local selection applied, specify the local selection in the ON
clause of the FULL OUTER JOIN, or use common table expressions. For example:

WITH TEMPEMP AS (SELECT * FROM CORPDATA.EMPLOYEE XXX WHERE SALARY > 10000)
SELECT EMPNO, LASTNAME, DEPTNAME
FROM TEMPEMP XXX
FULL OUTER JOIN CORPDATA.DEPARTMENT YYY
ON XXX.WORKDEPT = YYY.DEPTNO

Join cost estimation and index selection


As the query optimizer compares the various possible access choices, it must assign a numeric cost value
to each candidate. The optimizer uses that value to determine the implementation which consumes the
least amount of processing time. This costing value is a combination of CPU and I/O time
In steps 3 and 5 in “Join order optimization” on page 71, the optimizer estimates cost and chooses an
access method for a given dial combination. The choices made are like the choices for row selection,
except that a plan using a probe must be chosen.
The costing value is based on the following assumptions:
• Table pages and index pages must be retrieved from auxiliary storage. For example, the query
optimizer is not aware that an entire table might be loaded into active memory as the result of a
Set Object Access (SETOBJACC) CL command. Use of this command could significantly improve
the performance of a query. However, the optimizer does not change the query implementation to take
advantage of the memory resident state of the table.
• The query is the only process running on the system. No allowance is given for system CPU utilization
or I/O waits which occur because of other processes using the same resources. CPU-related costs are
scaled to the relative processing speed of the system running the query.
• The values in a column are uniformly distributed across the table. For example, if 10% of the table rows
have the same value, then on average, every 10th row in the table contains that value.
• The column values are independent from any other column values in a row, unless there is an index
available whose key definition is (A, B). Multi-key field indexes allow the optimizer to detect when the
values between columns are correlated.
For example, a column named A has a value of 1 in 50% of the rows in a table. A column named B has a
value of 2 in 50% of the rows. It is expected that a query which selects rows where A = 1, and B = 2
selects 25% of the rows in the table.
The main factors in the join cost calculation for secondary dials are:
• the number of rows selected in all previous dials
• the number of rows which match, on average, each of the rows selected from previous dials.
Both of these factors can be derived by estimating the number of matching rows for a given dial.
When the join operator is something other than equal, the expected number of matching rows is based on
the following default filter factors:
• 33% for less-than, greater-than, less-than-equal-to, or greater-than-equal-to
• 90% for not equal

Database performance and query optimization 73


• 25% for BETWEEN range (OPNQRYF %RANGE)
• 10% for each IN list value (OPNQRYF %VALUES)
For example, when the join operator is less-than, the expected number of matching rows is 0.33 *
(number of rows in the dial). If no join specifications are active for the current dial, the Cartesian product
is assumed to be the operator. For Cartesian products, the number of matching rows is every row in the
dial, unless local row selection can be applied to the index.
When the join operator is equal, the expected number of rows is the average number of duplicate rows for
a given value.
Related information
Set Object Access (SETOBJACC) command

Transitive closure predicates


For join queries, the query optimizer could do some special processing to generate additional selection.
When the set of predicates that belong to a query logically infer extra predicates, the query optimizer
generates additional predicates. The purpose is to provide more information during join optimization.
See the following examples:

SELECT * FROM EMPLOYEE, EMP_ACT


WHERE EMPLOYEE.EMPNO = EMP_ACT.EMPNO
AND EMPLOYEE.EMPNO = '000010'

The optimizer modifies the query to:

SELECT * FROM EMPLOYEE, EMP_ACT


WHERE EMPLOYEE.EMPNO = EMP_ACT.EMPNO
AND EMPLOYEE.EMPNO = '000010'
AND EMP_ACT.EMPNO = '000010'

The following rules determine which predicates are added to other join dials:
• The dials affected must have join operators of equal.
• The predicate is isolatable, which means that a false condition from this predicate omits the row.
• One operand of the predicate is an equal join column and the other is a constant or host variable.
• The predicate operator is not LIKE (OPNQRYF %WLDCRD, or *CT).
• The predicate is not connected to other predicates by OR.
The query optimizer generates a new predicate, whether a predicate exists in the WHERE clause
(OPNQRYF QRYSLT parameter).
Some predicates are redundant. Redundant predicates occur when a previous evaluation of other
predicates in the query already determines the result that predicate provides. Redundant predicates
can be specified by you or generated by the query optimizer during predicate manipulation. Redundant
predicates with operators of =, >, >=, <, <=, or BETWEEN (OPNQRYF *EQ, *GT, *GE, *LT, *LE, or %RANGE)
are merged into a single predicate to reflect the most selective range.

Look ahead predicate generation (LPG)


A special type of transitive closure called look ahead predicate generation (LPG) might be costed for joins.
In this case, the optimizer tries to minimize the random I/O of a join by pre-applying the query results to
a large fact table. LPG is typically used with a class of queries referred to as star join queries. However, it
can possibly be used with any join query.
Look at the following query:

SELECT * FROM EMPLOYEE,EMP_ACT


WHERE EMPLOYEE.EMPNO = EMP_ACT.EMPNO
AND EMPLOYEE.EMPNO ='000010'

74 IBM i: Performance and Query Optimization


The optimizer could decide to internally modify the query to be:

WITH HT AS (SELECT *
FROM EMPLOYEE
WHERE EMPLOYEE.EMPNO='000010')

SELECT *
FROM HT, EMP_ACT
WHERE HT.EMPNO = EMP_ACT.EMPNO
AND EMP_ACT.EMPNO IN (SELECT DISTINCT EMPNO
FROM HT)

The optimizer places the results of the "subquery" into a temporary hash table. The hash table of the
subquery can be applied in one of two methods against the EMP_ACT (fact) table:
• The distinct values of the hash tables are retrieved. For each distinct value, an index over EMP_ACT is
probed to determine which records are returned for that value. Those record identifiers are normally
then stored and sorted (sometimes the sorting is omitted, depending on the total number of record
ids expected). Once the ids are determined, the subset of EMP_ACT records can be accessed more
efficiently than in a traditional nested loop join processing.
• EMP_ACT can be scanned. For each record, the hash table is probed to see if the record joins at all to
EMPLOYEE. This method allows for efficient access to EMP_ACT with a more efficient record rejection
method than in a traditional nested loop join process.
Note: LPG processing is part of the normal processing in the SQL Query Engine. CQE only considers the
first method, requires that the index in question by an EVI and also requires use of the STAR_JOIN and
FORCE_JOIN_ORDER QAQQINI options.

Tips for improving performance when selecting data from more than two
tables
The following suggestion is only applicable to CQE and is directed specifically to select-statements that
access several tables. For joins that involve more than two tables, you might want to provide redundant
information about the join columns. The CQE optimizer does not generate transitive closure predicates
between two columns. If you give the optimizer extra information to work with when requesting a join,
it can determine the best way to do the join. The additional information might seem redundant, but is
helpful to the optimizer.
If the select-statement you are considering accesses two or more tables, all the recommendations
suggested in “Creating an index strategy” on page 259 apply. For example, instead of coding:

EXEC SQL
DECLARE EMPACTDATA CURSOR FOR
SELECT LASTNAME, DEPTNAME, PROJNO, ACTNO
FROM CORPDATA.DEPARTMENT, CORPDATA.EMPLOYEE,
CORPDATA.EMP_ACT
WHERE DEPARTMENT.MGRNO = EMPLOYEE.EMPNO
AND EMPLOYEE.EMPNO = EMP_ACT.EMPNO
END-EXEC.

Provide the optimizer with a little more data and code:

EXEC SQL
DECLARE EMPACTDATA CURSOR FOR
SELECT LASTNAME, DEPTNAME, PROJNO, ACTNO
FROM CORPDATA.DEPARTMENT, CORPDATA.EMPLOYEE,
CORPDATA.EMP_ACT
WHERE DEPARTMENT.MGRNO = EMPLOYEE.EMPNO
AND EMPLOYEE.EMPNO = EMP_ACT.EMPNO
AND DEPARTMENT.MGRNO = EMP_ACT.EMPNO
END-EXEC.

Multiple join types for a query


Multiple join types (inner, left outer, right outer, left exception, and right exception) can be specified in the
query using the JOIN syntax. However, the Db2 for i can only support one join type of inner, left outer, or

Database performance and query optimization 75


left exception join for the entire query. The optimizer determines the overall join type for the query and
reorders the files to achieve the correct semantics.
Note: This section does not apply to SQE or OPNQRYF.
The optimizer evaluates the join criteria, along with any row selection, to determine the join type for each
dial and the entire query. Then the optimizer generates additional selection using the relative row number
of the tables to simulate the different types of joins that occur within the query.
Null values are returned for any unmatched rows in either a left outer or an exception join. Any isolatable
selection specified for that dial, including any additional join criteria specified in the WHERE clause,
causes all the unmatched rows to be eliminated. (The exception is when the selection is for an IS NULL
predicate.) This elimination causes the dial join type to change to an inner join (or an exception join) if the
IS NULL predicate was specified.
In the following example, a left outer join is specified between the tables EMPLOYEE and DEPARTMENT.
In the WHERE clause, there are two selection predicates that also apply to the DEPARTMENT table.

SELECT EMPNO, LASTNAME, DEPTNAME, PROJNO


FROM CORPDATA.EMPLOYEE XXX LEFT OUTER JOIN CORPDATA.DEPARTMENT YYY
ON XXX.WORKDEPT = YYY.DEPTNO
LEFT OUTER JOIN CORPDATA.PROJECT ZZZ
ON XXX.EMPNO = ZZZ.RESPEMP
WHERE XXX.EMPNO = YYY.MGRNO AND
YYY.DEPTNO IN ('A00', 'D01', 'D11', 'D21', 'E11')

The first selection predicate, XXX.EMPNO = YYY.MGRNO, is an additional join condition that is evaluated
as an "inner join" condition. The second is an isolatable selection predicate that eliminates any
unmatched rows. Either of these predicates can cause the join type for the DEPARTMENT table to change
from a left outer join to an inner join.
Even though the join between the EMPLOYEE and DEPARTMENT tables was changed to an inner join, the
entire query remains a left outer join to satisfy the join condition for the PROJECT table.
Note: Care must be taken when specifying multiple join types since they are supported by appending
selection to the query for any unmatched rows. The number of rows satisfying the join criteria can
become large before selection that either selects or omits the unmatched rows based on that individual
dial join type is applied.

Sources of join query performance problems


The optimization algorithms described earlier benefit most join queries, but the performance of a few
queries might be degraded.
This occurs when:
• An index is not available which provides average number of duplicate values statistics for the potential
join columns.
• The optimizer uses default filter factors to estimate the number of rows when applying local selection to
the table when indexes or column statistics do not exist over the selection columns.
Creating indexes over the selection columns allows the optimizer to make a more accurate filtering
estimate by using key range estimates.
• The particular values selected for the join columns yield a greater number of matching rows than the
average number of duplicate values for all values of the join columns in the table. For example, the data
is not uniformly distributed.

76 IBM i: Performance and Query Optimization


Join performance tips
If you have a join query performing poorly, or you are creating an application which uses join queries,
these tips could be useful.

Table 31. Checklist for Creating an Application that Uses Join Queries
What to Do How It Helps
Check the database design. The query optimizer can select an efficient access method because it can
Make sure that there are determine the average number of duplicate values. Many queries could use
indexes available over all the the existing index and avoid the cost of creating a temporary index or hash
join columns and row selection table.
columns or both. The optimizer
provides index advice in several
places to aid in this process:
• the index advisor under
System i Navigator - Database
• the advised information under
Visual Explain
• the advised information in the
3020 record in the database
monitor

Check the query to see whether The query optimizer does not add predicates for predicates connected by OR
some complex predicates could or non-isolatable predicates, or predicate operator LIKE. Modify the query by
be added to other dials to adding additional predicates to help.
allow the optimizer to get better
selectivity for each dial.
Specify The query is creating a temporary index or hash table, and the processing
ALWCPYDTA(*OPTIMIZE) or time could be better if the existing index or hash table was used. Specify
ALWCPYDTA(*YES) ALWCPYDTA(*YES).
The query is not creating a temporary index or hash table, and the
processing time could be better if a temporary index was created. Specify
ALWCPYDTA(*OPTIMIZE).
Alternatively, specify OPTIMIZE FOR n ROWS to inform the optimizer that the
application reads every resulting row. Set n to a large number. You can also
set n to a small number before ending the query.

For OPNQRYF, specify Specify the OPTIMIZE(*FIRSTIO) or OPTIMIZE(*ALLIO) option to accurately


OPTIMIZE(*FIRSTIO) or reflect your application. Use *FIRSTIO, if you want the optimizer to optimize
OPTIMIZE(*ALLIO) the query to retrieve the first block of rows most efficiently. This biases the
optimizer toward using existing objects. If you want to optimize the retrieval
time for the entire answer set, use *ALLIO. This option could cause the
optimizer to create temporary indexes or hash tables to minimize I/O.

Database performance and query optimization 77


Table 31. Checklist for Creating an Application that Uses Join Queries (continued)
What to Do How It Helps
Star join queries A join in which one table is joined with all secondary tables consecutively
is sometimes called a star join. If all secondary join predicates contain a
column reference to a particular table, place that table in join position one.
In Example A, all tables are joined to table EMPLOYEE. The query optimizer
can freely determine the join order. For SQE, the optimizer uses Look Ahead
Predicate generation to determine the optimal join order. For CQE, the query
could be changed to force EMPLOYEE into join position one by using the
query options file (QAQQINI) FORCE_JOIN_ORDER parameter of *YES. In
these examples, the join type is a join with no default values returned
(an inner join.). The reason for forcing the table into the first position is
to avoid random I/O processing. If EMPLOYEE is not in join position one,
every row in EMPLOYEE can be examined repeatedly during the join process.
If EMPLOYEE is fairly large, considerable random I/O processing occurs
resulting in poor performance. By forcing EMPLOYEE to the first position,
random I/O processing is minimized.
Example A: Star join query

DECLARE C1 CURSOR FOR


SELECT * FROM DEPARTMENT, EMP_ACT, EMPLOYEE,
PROJECT
WHERE DEPARTMENT.DEPTNO=EMPLOYEE.WORKDEPT
AND EMP_ACT.EMPNO=EMPLOYEE.EMPNO
AND EMPLOYEE.WORKDEPT=PROJECT.DEPTNO

Example B: Star join query with order forced using FORCE_JOIN_ORDER

DECLARE C1 CURSOR FOR


SELECT * FROM EMPLOYEE, DEPARTMENT, EMP_ACT,
PROJECT
WHERE DEPARTMENT.DEPTNO=EMPLOYEE.WORKDEPT
AND EMP_ACT.EMPNO=EMPLOYEE.EMPNO
AND EMPLOYEE.WORKDEPT=PROJECT.DEPTNO

Specify Ordering is specified and all key columns are from a single dial. The optimizer
ALWCPYDTA(*OPTIMIZE) to can consider all possible join orders with ALWCPYDTA(*OPTIMIZE).
allow the query optimizer to use
a sort routine.
Specify join predicates to Improves performance by reducing the join fan-out. It is best if every
prevent all the rows from one secondary table has at least one join predicate that references one of its
table from being joined to every columns as a 'join-to' column.
row in the other table.

Distinct optimization
Distinct is used to compare a value with another value.
There are two methods to write a query that returns distinct values in SQL. One method uses the
DISTINCT keyword:

SELECT DISTINCT COL1, COL2


FROM TABLE1

The second method uses GROUP BY:

SELECT COL1, COL2


FROM TABLE1
GROUP BY COL1, COL2

78 IBM i: Performance and Query Optimization


All queries that contain a DISTINCT, and are run using SQE, rewritten into queries using GROUP BY. This
rewrite enables queries using DISTINCT to take advantage of the many grouping techniques available to
the optimizer.

Distinct to Grouping implementation


The following example query has a DISTINCT:

SELECT DISTINCT COL1, COL2


FROM T1
WHERE COL2 > 5 AND COL3 = 2

The optimizer rewrites it into this query:

SELECT COL1, COL2


FROM T1
WHERE COL2 > 5 AND COL3 = 2
GROUP BY COL1, COL2

Distinct removal
A query containing a DISTINCT over whole-file aggregation (no grouping or selection) allows the
DISTINCT to be removed. For example, look at this query with DISTINCT:

SELECT DISTINCT COUNT(C1), SUM(C1)


FROM TABLE1

The optimizer rewrites this query as the following:

SELECT COUNT(C1), SUM(C1)


FROM TABLE1

If the DISTINCT and the GROUP BY fields are identical, the DISTINCT can be removed. If the DISTINCT
fields are a subset of the GROUP BY fields (and there are no aggregates), the DISTINCTs can be removed.

Grouping optimization
Db2 for i has certain techniques to use when the optimizer encounters grouping. The query optimizer
chooses its methods for optimizing your query.

Hash grouping implementation


This technique uses the base hash access method to perform grouping or summarization of the selected
table rows. For each selected row, the specified grouping value is run through the hash function.
The computed hash value and grouping value are used to quickly find the entry in the hash table
corresponding to the grouping value.
If the current grouping value already has a row in the hash table, the hash table entry is retrieved
and summarized (updated) with the current table row values based on the requested grouping column
operations (such as SUM or COUNT). If a hash table entry is not found for the current grouping value, a
new entry is inserted into the hash table and initialized with the current grouping value.
The time required to receive the first group result for this implementation is most likely longer than
other grouping implementations because the hash table must be built and populated first. Once the
hash table is populated, the database manager uses the table to start returning the grouping results.
Before returning any results, the database manager must apply any specified grouping selection criteria
or ordering to the summary entries in the hash table.

Where the hash grouping method is most effective


The hash grouping method is most effective when the consolidation ratio is high. The consolidation ratio
is the ratio of the selected table rows to the computed grouping results. If every database table row has

Database performance and query optimization 79


its own unique grouping value, then the hash table becomes too large. The size in turn slows down the
hashing access method.
The optimizer estimates the consolidation ratio by first determining the number of unique values in the
specified grouping columns (that is, the expected number of groups in the database table). The optimizer
then examines the total number of rows in the table and the specified selection criteria and uses the
result of this examination to estimate the consolidation ratio.
Indexes over the grouping columns can help make the ratio estimate of the optimizer more accurate.
Indexes improve the accuracy because they contain statistics that include the average number of
duplicate values for the key columns.
The optimizer also uses the expected number of groups estimate to compute the number of partitions in
the hash table. As mentioned earlier, the hashing access method is more effective when the hash table is
well-balanced. The number of hash table partitions directly affects how entries are distributed across the
hash table and the uniformity of this distribution.
The hash function performs better when the grouping values consist of columns that have non-numeric
data types, except for the integer (binary) data type. In addition, specifying grouping value columns that
are not associated with the variable length and null column attributes allows the hash function to perform
more effectively.

Index grouping implementation


There are two primary ways to implement grouping using an index: Ordered grouping and pre-
summarized processing.

Ordered grouping
This implementation uses the Radix Index Scan or the Radix Index Probe access methods to perform the
grouping. An index is required that contains all the grouping columns as contiguous leftmost key columns.
The database manager accesses the individual groups through the index and performs the requested
summary functions.
Since the index, by definition, already has all the key values grouped, the first group result can be
returned in less time than the hashing method. This index performance is faster because the hashing
method requires a temporary result. This implementation can be beneficial if an application does not
need to retrieve all the group results, or if an index exists that matches the grouping columns.
When the grouping is implemented with an index and a permanent index does not exist that satisfies
grouping columns, a temporary index is created. The grouping columns specified within the query are
used as the key columns for this index.

Pre-summarized processing
This SQE-only implementation uses an Encoded Vector Index to extract the summary information already
in the symbol table of the index. The EVI symbol table contains the unique key values and a count of the
number of table records that have that unique value. The grouping for the columns of the index key is
already performed. If the query references a single table and performs simple aggregation, the EVI might
be used for quick access to the grouping results. For example, consider the following query:

SELECT COUNT(*), col1


FROM t1
GROUP BY col1

If an EVI exists over t1 with a key of col1, the optimizer can rewrite the query to access the precomputed
grouping answer in the EVI symbol table.
This rewrite can result in dramatic improvements when the number of table records is large and the
number of resulting groups is small, relative to the size of the table.
This method is also possible with selection (WHERE clause), as long as the reference columns are in the
key definition of the EVI.

80 IBM i: Performance and Query Optimization


For example, consider the following query:

SELECT COUNT(*), col1


FROM t1
WHERE col1 > 100
GROUP BY col1

This query can be rewritten by the optimizer to use the EVI. This pre-summarized processing works for
DISTINCT processing, GROUP BY and for column function COUNT. All columns of the table referenced in
the query must also be in the key definition of the EVI.
So, for example, the following query can be made to use the EVI:

SELECT DISTINCT col1


FROM t1

However, this query cannot:

SELECT DISTINCT col1


FROM t1
WHERE col2 > 1

This query cannot use the EVI because it references col2 of the table, which is not in the key definition of
the EVI. If multiple columns are defined in the EVI key, for example, col1 and col2, it is important to use
the left-most columns of the key. For example, if an EVI existed with a key definition of (col1, col2), but
the query referenced only col2, it is unlikely the EVI is used.

EVI INCLUDE aggregates


A more powerful example of pre-summarized processing can be facilitated by the use of the INCLUDE
keyword on the index create. By default, COUNT(*) is implied on the creation of an EVI. Additional
numeric aggregates specified over non-key data can further facilitate pre-determined or ready-made
aggregate results during query optimization.
For example, suppose the following query is a frequently requested result set, queried in whole or as part
of a subquery comparison.

SELECT AVG(col2)
FROM t1
GROUP BY col1

Create the following EVI to predetermine the value of AVG(col2).

CREATE ENCODED VECTOR INDEX eviT1 ON t1(col1) INCLUDE(AVG(col2))

eviT1 delivers distinct values for col1 and COUNT(*) specific to the group by of col1. eviT1 can be used
to generate an asynchronous bitmap or RRN list for accessing the table rows for specific col1 values. In
addition, eviT1 computes an additional aggregate, AVG(col2), over the same group by column (col1) by
specifying the INCLUDE aggregate.
INCLUDE aggregates are limited to those aggregates that result in numeric values: SUM, COUNT, AVG,
STDDEV, and so on. These values can be readily maintained as records are inserted, deleted, or updated
in the base table.
MIN or MAX are two aggregates that are not supported as INCLUDE aggregates. Deleting the current row
contributing to the MIN or MAX value would result in the need to recalculate, potentially accessing many
rows, and reducing performance.
INCLUDE values can also contain aggregates over derivations. For example, if you have a couple
of columns that contribute to an aggregate, that derivation can be specified, for example, as
SUM(col1+col2+col3).
It is recommended that EVIs with INCLUDE aggregates only contain references to columns or column-
specific derivations, for example, SUM(salary+bonus).

Database performance and query optimization 81


In many environments, queries that contain derivations using constants convert those constants to
parameter markers. This conversion allows a much higher degree of ODP reuse. However, it can be more
difficult to match the parameter value to a literal in the index definition.
The optimizer does attempt to match constants in the EVI with parameter markers or host variable values
in the query. However, in some complex cases this support is limited and could result in the EVI not
matching the query.
Pre-summarized processing can also take advantage of EVIs with INCLUDE in a JOIN situation.
For example, see the following aggregate query over the join of two tables.

EVI INCLUDE aggregate example

SELECT deptname, sum(salary)


FROM DEPARTMENT, EMPLOYEE
WHERE deptno=workdept
GROUP BY deptname

By providing an EVI with INCLUDE index, as follows, and with optimizer support to push down aggregates
to the table level when possible, the resulting implementation takes advantage of the ready-made
aggregates already supplied by EVI employeeSumByDept. The implementation never needs to touch or
aggregate rows in the Employee table.

CREATE ENCODED VECTOR INDEX employeeSumByDept ON employee(workdept)


INCLUDE(sum(salary))

Aggregate pushdown results in a rewrite with EVI INCLUDE implementation, conceptually like the
following query.

SELECT deptname, sum(sum(salary))


FROM department,
(SELECT workdept, sum(salary) FROM employee group by workdept) employee_2
WHERE deptno=workdept

Instead of department joining to all the rows in the employee table, it now has the opportunity to join to
the predetermined aggregates, the sum of salary by department number, in the EVI symbol table. This
results in significant reduction in processing and IO.
Related concepts
How the EVI works
EVIs work in different ways for costing and implementation.
Related reference
Encoded vector index symbol table scan
An encoded vector index symbol table scan operation is used to retrieve the entries from the symbol table
portion of the index.

Whole table COUNT(*) grouping implementation


A special access method is available for handling grouping queries that only use COUNT(*).
For queries that meet all of the following criteria, a special access method of retrieving the record count
from the dataspace is used.
• the only aggregate function specified is COUNT(*) or COUNT of a non-null capable expression
• only one table is referenced
• no WHERE clause is specified
• no GROUP BY clause is specified
• the commitment control level is *NONE or Uncommitted Read
This appears as a TableScan in Visual Explain.

82 IBM i: Performance and Query Optimization


Optimizing grouping by eliminating grouping columns
All the grouping columns are evaluated to determine if they can be removed from the list of grouping
columns. Only those grouping columns that have isolatable selection predicates with an equal operator
specified can be considered. This guarantees that the column can only match a single value and does not
help determine a unique group.
This processing allows the optimizer to consider more indexes to implement the query. It also reduces the
number of columns that are added as key columns to a temporary index or hash table.
The following example illustrates a query where the optimizer might eliminate a grouping column.

DECLARE DEPTEMP CURSOR FOR


SELECT EMPNO, LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = '000190'
GROUP BY EMPNO, LASTNAME, WORKDEPT

OPNQRYF example:

OPNQRYF FILE(EMPLOYEE) FORMAT(FORMAT1)


QRYSLT('EMPNO *EQ ''000190''')
GRPFLD(EMPNO LASTNAME WORKDEPT)

In this example, the optimizer can remove EMPNO from the list of grouping columns because of the
EMPNO = '000190' selection predicate. An index that only has LASTNAME and WORKDEPT specified as
key columns could implement the query. If a temporary index or hash is required then EMPNO is not used.
Note: Even though EMPNO can be removed from the list of grouping columns, the optimizer might use a
permanent index that exists with all three grouping columns.

Optimizing grouping by adding additional grouping columns


The same logic that is applied to removing grouping columns can also be used to add additional grouping
columns to the query. Additional grouping columns are added only when you are trying to determine if an
index can be used to implement the grouping.
The following example illustrates a query where the optimizer might add an additional grouping column.

CREATE INDEX X1 ON EMPLOYEE


(LASTNAME, EMPNO, WORKDEPT)

DECLARE DEPTEMP CURSOR FOR


SELECT LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = '000190'
GROUP BY LASTNAME, WORKDEPT

For this query request, the optimizer can add EMPNO as an additional grouping column when considering
X1 for the query.

Optimizing grouping by using index skip key processing


Index Skip Key processing can be used when grouping with the keyed sequence implementation
algorithm which uses an existing index. It is a specialized version of ordered grouping that processes
few records in each group rather than all records in each group.
The index skip key processing algorithm:
1. Uses the index to position to a group and
2. finds the first row matching the selection criteria for the group, and if specified the first non-null MIN
or MAX value in the group
3. Returns the group to the user
4. "Skip" to the next group and repeat processing

Database performance and query optimization 83


This algorithm improves performance by potentially not processing all index key values for a group.
Index skip key processing can be used:
• For single table queries using the keyed sequence grouping implementation when:
– There are no column functions in the query, or
– There is only a single MIN or MAX column function and the MIN or MAX operand is the next index key
column after the grouping columns. There can be no other grouping functions in the query. For the
MIN function, the key column must be an ascending key; for the MAX function, the key column must
be a descending key. If the query is whole table grouping, the operand of the MIN or MAX must be the
first key column.
Example 1, using SQL:

CREATE INDEX IX1 ON EMPLOYEE (SALARY DESC)

DECLARE C1 CURSOR FOR


SELECT MAX(SALARY) FROM EMPLOYEE;

The query optimizer chooses to use the index IX1. The SLIC runtime code scans the index until
it finds the first non-null value for SALARY. Assuming that SALARY is not null, the runtime code
positions to the first index key and return that key value as the MAX of salary. No more index keys are
processed.
Example 2, using SQL:

CREATE INDEX IX2 ON EMPLOYEE (WORKDEPT, JOB, SALARY)

DECLARE C1 CURSOR FOR


SELECT WORKDEPT, MIN(SALARY)
FROM EMPLOYEE
WHERE JOB='CLERK'
GROUP BY WORKDEPT

The query optimizer chooses to use Index IX2. The database manager positions to the first group for
DEPT where JOB equals 'CLERK' and returns the SALARY. The code then skips to the next DEPT group
where JOB equals 'CLERK'.
• For join queries:
– All grouping columns must be from a single table.
– For each dial, there can be at most one MIN or MAX column function operand that references the dial.
No other column functions can exist in the query.
– If the MIN or MAX function operand is from the same dial as the grouping columns, then it uses the
same rules as single table queries.
– If the MIN or MAX function operand is from a different dial, then the join column for that dial must
join to one of the grouping columns. The index for that dial must contain the join columns followed by
the MIN or MAX operand.
Example 1, using SQL:

CREATE INDEX IX1 ON DEPARTMENT(DEPTNAME)

CREATE INDEX IX2 ON EMPLOYEE(WORKDEPT, SALARY)

DECLARE C1 CURSOR FOR


SELECT DEPARTMENT.DEPTNO, MIN(SALARY)
FROM DEPARTMENT, EMPLOYEE
WHERE DEPARTMENT.DEPTNO=EMPLOYEE.WORKDEPT
GROUP BY DEPARTMENT.DEPTNO;

84 IBM i: Performance and Query Optimization


Optimizing grouping by removing read triggers
For queries involving physical files or tables with read triggers, group by triggers always involve a
temporary file before the group by processing. Therefore, these queries slow down.
Note: Read triggers are added when the Add Physical File Trigger (ADDPFTRG) command has
been used on the table with TRGTIME (*AFTER) and TRGEVENT (*READ).
The query runs faster if the read trigger is removed (RMVPFTRG TRGTIME (*AFTER) TRGEVENT (*READ)).
Related information
Add Physical File Trigger (ADDPFTRG) command

Grouping set optimization


The optimizer uses all the previously mentioned grouping optimizations for individual grouping sets
specified in the query.
If multiple temporary result sets are needed to implement all the grouping sets, they can all be populated
using one pass through the data. This one-pass population occurs even if different types of temporary
result sets are used to implement various grouping sets.
A temporary result type called sorted distinct list is used specifically for ROLLUP implementations.
This temporary result set is used to compute the aggregate rows: the grouping set that includes all
expressions listed in the ROLLUP clause. Hash grouping is used internally to quickly find the current
grouping value. The entries in the temporary result sets are also sorted. This sorting allows the aggregate
results to be used to compute the super-aggregate rows in the rollup result set without creating additional
temporary result sets.
ROLLUPs can also be implemented using a radix index over the columns in the rollup without creating a
temporary result set.
The optimizer can compute all the grouping sets in a given ROLLUP using at most one temporary result
set. Therefore, it is advantageous for the optimizer to look for the rollup pattern in grouping set queries.
The optimizer tries to find the ROLLUP pattern in a list of individual grouping sets. For example, the
following GROUP BY clause:

GROUP BY GROUPING SETS ((A, B, C), (B, D), (A, B), (A), ())

is rewritten to:

GROUP BY GROUPING SETS ((ROLLUP(A, B, C)), (B, D))

This rewrite allows the query to be implemented using at most two temporary results sets rather than 4.
Queries containing a CUBE clause is broken down into a union of ROLLUPs and grouping sets. For
example:

CUBE(A, B, C)

is equivalent to:

(ROLLUP(A, B, C)), (ROLLUP'(B, C)), (ROLLUP'(C, A))

The ROLLUP' notation is an internal representation of a ROLLUP operation that does not include a grand
total row in its result set. So, ROLLUP'(B, C) is equivalent to GROUP BY GROUPING SETS ((B,C), (B)). This
CUBE rewrite implements at most three temporary result sets, rather than the 8 that might be needed had
the query not been rewritten.

Database performance and query optimization 85


Ordering optimization
This section describes how Db2 for i implements ordering techniques, and how optimization choices are
made by the query optimizer. The query optimizer can use either index ordering or a sort to implement
ordering.

Sort Ordering implementation


The sort algorithm reads the rows into a sort space and sorts the rows based on the specified ordering
keys. The rows are then returned to the user from the ordered sort space.

Index Ordering implementation


The index ordering implementation requires an index that contains all the ordering columns as contiguous
leftmost key columns. The database manager accesses the individual rows through the index in index
order, which results in the rows being returned in order to the requester.
This implementation can be beneficial if an application does not need to retrieve all the ordered results,
or if an index exists that matches the ordering columns. When the ordering is implemented with an index,
and a permanent index does not exist that satisfies ordering columns, a temporary index is created. The
ordering columns specified within the query are used as the key columns for this index.

Index Merge Ordering Implementation


Index Merge Ordering takes some of the features of both index and sorted ordering by using an index to
apply the selection and then using an indexed list to sort the rows. This optimization is primarily aimed at
queries that have an optimization goal of *FIRSTIO and the WHERE clause selection contains non-equal
predicates.

Optimizing ordering by eliminating ordering columns


All the ordering columns are evaluated to determine if they can be removed from the list of ordering
columns. Only those ordering columns that have isolatable selection predicates with an equal operator
specified can be considered. This guarantees that the column can match only a single value, and does not
help determine in the order.
In general, for an index to be eligible for Index Merge Ordering, the index should be created as follows:
• Any columns with equal predicates that are not in the ORDER BY list should be first keys in the index.
• Followed by any columns for non-equal predicates that are not in the ORDER BY list. The columns
should be arranged so the most selective predicate column is the first column following the equal
predicate columns.
• Followed by the ORDER BY columns in the same order as the ORDER BY clause of the query and with
the same ASC or DESC attribute.
• Optionally, at the end you may include other selection columns or other selected columns for Index
Only Access.
For example:

SELECT * FROM SALES


WHERE SALES_DATE BETWEEN '1996-03-29' AND '1996-04-29'
AND REGION IN ('Quebec','Manitoba')
ORDER BY SALES_PERSON

The Index to create would be with keys:

SALES_DATE, REGION, SALES_PERSON

In order to allow a more general indexing scheme, it is possible to use an index for index merge ordering
even if there are leading keys not used in the query. The above index could also be used for the following
query:

86 IBM i: Performance and Query Optimization


SELECT SALES_DATE, REGION, SALES_PERSON, SALES
FROM SALES
WHERE REGION IN ('Quebec','Manitoba')
ORDER BY SALES_PERSON

If SALES was added as a trailing key, then Index Only Access would be used for both queries.

CREATE INDEX SALES_IMOX ON SALES (SALES_DATE, REGION, SALES_PERSON, SALES)

The optimizer can now consider more indexes as it implements the query. The number of columns that
are added as key columns to a temporary index is also reduced. The following SQL example illustrates a
query where the optimizer might eliminate an ordering column.

DECLARE DEPTEMP CURSOR FOR


SELECT EMPNO, LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = '000190'
ORDER BY EMPNO, LASTNAME, WORKDEPT

Optimizing ordering by adding additional ordering columns


The same logic that is applied to removing ordering columns can also be used to add additional grouping
columns to the query. This logic is done only when you are trying to determine if an index can be used to
implement the ordering.
The following example illustrates a query where the optimizer might add an additional ordering column.

CREATE INDEX X1 ON EMPLOYEE (LASTNAME, EMPNO, WORKDEPT)

DECLARE DEPTEMP CURSOR FOR


SELECT LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = '000190'
ORDER BY LASTNAME, WORKDEPT

For this query request, the optimizer can add EMPNO as an additional ordering column when considering
X1 for the query.

Index Ordering Implementation Using Reverse Ordered Indexes


It is also possible to use reverse ordered indexes to provide ordering. In that case, the index keys for all
ORDER BY columns must be reversed. The database manager will process the index in reverse order by
starting at the end and reading through the index backwards.
The following index and query illustrates an example where the optimizer could use a reversed ordered
index.

CREATE INDEX CORPDATA.INDEX1 ON CORPDATA.EMPLOYEE (SALARY ASC, LASTNAME DESC)

SELECT EMPNO, LASTNAME, WORKDEPT, SALARY


FROM CORPDATA.EMPLOYEE
ORDER BY SALARY DESC, LASTNAME ASC

View implementation
Views, derived tables (nested table expressions or NTEs), and common table expressions (CTEs) are
implemented by the query optimizer using one of two methods.
These methods are:
• The optimizer combines the query select statement with the select statement of the view.
• The optimizer places the results of the view in a temporary table and then replaces the view reference in
the query with the temporary table.

Database performance and query optimization 87


View composite implementation
The view composite implementation takes the query select statement and combines it with the select
statement of the view to generate a new query. The new, combined select statement query is then run
directly against the underlying base tables.
This single, composite statement is the preferred implementation for queries containing views, since it
requires only a single pass of the data.
See the following examples:

CREATE VIEW D21EMPL AS


SELECT * FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT='D21'

Using SQL:

SELECT LASTNAME, FIRSTNME, SALARY


FROM D21EMPL
WHERE JOB='CLERK'

The query optimizer generates a new query that looks like the following example:

SELECT LASTNAME, FIRSTNME, SALARY


FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT='D21' AND JOB='CLERK'

The query contains the columns selected by the user query, the base tables referenced in the query, and
the selection from both the view and the user query.
Note: The new composite query that the query optimizer generates is not visible to users. Only the
original query against the view is seen by users and database performance tools.

View materialization implementation


The view materialization implementation runs the query of the view and places the results in a temporary
result. The view reference in the user query is then replaced with the temporary, and the query is run
against the temporary result.
View materialization is done whenever it is not possible to create a view composite. For SQE, view
materialization is optional. The following types of queries require view materialization:
• The outermost view select contains grouping, the query contains grouping, and refers to a column
derived from a column function in the view HAVING or select-list.
• The query is a join and the outermost select of the view contains grouping or DISTINCT.
• The outermost select of the view contains DISTINCT, and the query has UNION, grouping, or DISTINCT
and one of the following:
– Only the query has a shared weight NLSS table
– Only the view has a shared weight NLSS table
– Both the query and the view have a shared weight NLSS table, but the tables are different.
• The query contains a column function and the outermost select of the view contains a DISTINCT
• The view does not contain an access plan. Occurs when a view references a view, and a view composite
cannot be created because of one of the previous listed reasons. Does not apply to nested table
expressions and common table expressions.
• The Common table expression (CTE) is referenced more than once in the query FROM clause. Also, the
CTE SELECT clause references a MODIFIES or EXTERNAL ACTION UDF.
When a temporary result table is created, access methods that are allowed with ALWCPYDTA(*OPTIMIZE)
could be used to implement the query. These methods include hash grouping, hash join, and bitmaps.

88 IBM i: Performance and Query Optimization


See the following examples:

CREATE VIEW AVGSALVW AS


SELECT WORKDEPT, AVG(SALARY) AS AVGSAL
FROM CORPDATA.EMPLOYEE
GROUP BY WORKDEPT

SQL example:

SELECT D.DEPTNAME, A.AVGSAL


FROM CORPDATA.DEPARTMENT D, AVGSALVW A
WHERE D.DEPTNO=A.WORKDEPT

In this case, a view composite cannot be created since a join query references a grouping view.
The results of AVGSALVW are placed in a temporary result table (*QUERY0001). The view reference
AVGSALVW is replaced with the temporary result table. The new query is then run. The generated query
looks like the following:

SELECT D.DEPTNAME, A.AVGSAL


FROM CORPDATA.DEPARTMENT D, *QUERY0001 A
WHERE D.DEPTNO=A.WORKDEPT

Note: The new query that the query optimizer generates is not visible to users. Only the original query
against the view is seen by users and database performance tools.
Whenever possible, isolatable selection from the query, except subquery predicates, is added to the view
materialization process. This results in smaller temporary result tables and allows existing indexes to be
used when materializing the view. This process is not done if there is more than one reference to the same
view or common table expression in the query. The following is an example where isolatable selection is
added to the view materialization:

SELECT D.DEPTNAME,A.AVGSAL
FROM CORPDATA.DEPARTMENT D, AVGSALVW A
WHERE D.DEPTNO=A.WORKDEPT AND
A.WORKDEPT LIKE 'D%' AND AVGSAL>10000

The isolatable selection from the query is added to the view resulting in a new query to generate the
temporary result table:

SELECT WORKDEPT, AVG(SALARY) AS AVGSAL


FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT LIKE 'D%'
GROUP BY WORKDEPT
HAVING AVG(SALARY)>10000

Materialized query table optimization


Materialized query tables (MQTs) (also referred to as automatic summary tables or materialized views)
can provide performance enhancements for queries.
This performance enhancement is done by precomputing and storing results of a query in the materialized
query table. The database engine can use these results instead of recomputing them for a user specified
query. The query optimizer looks for any applicable MQTs. The optimizer can implement the query using a
given MQT, provided it is a faster implementation choice.
Materialized Query Tables are created using the SQL CREATE TABLE statement. Alternatively, the ALTER
TABLE statement could be used to convert an existing table into a materialized query table. The REFRESH
TABLE statement is used to recompute the results stored in the MQT. For user-maintained MQTs, the
MQTs could also be maintained by the user using INSERT, UPDATE, and DELETE statements.
Related information
Create Table statement

Database performance and query optimization 89


MQT supported function
Although an MQT can contain almost any query, the optimizer only supports a limited set of query
functions when matching MQTs to user specified queries. The user-specified query and the MQT query
must both be supported by the SQE optimizer.
The supported function in the MQT query by the MQT matching algorithm includes:
• Single table and join queries
• WHERE clause
• GROUP BY and optional HAVING clauses
• ORDER BY
• FETCH FIRST n ROWS
• Views, common table expressions, and nested table expressions
• UNIONs
• Partitioned tables
There is limited support in the MQT matching algorithm for the following:
• Scalar subselects
• User Defined Functions (UDFs) and user-defined table functions
• Recursive Common Table Expressions (RCTE)
• The following scalar functions:
– ATAN2
– DAYNAME
– DBPARTITIONNAME
– DECRYPT_BIT
– DECRYPT_BINARY
– DECRYPT_CHAR
– DECRYPT_DB
– DIFFERENCE
– DLVALUE
– DLURLPATH
– DLURLPATHONLY
– DLURLSEVER
– DLURLSCHEME
– DLURLCOMPLETE
– ENCRYPT_AES
– ENCRYPT_RC2
– ENCRYPT_TDES
– GENERATE_UNIQUE
– GETHINT
– IDENTITY_VAL_LOCAL
– INSERT
– MONTHNAME
– MONTHS_BETWEEN
– NEXT_DAY
– RAND

90 IBM i: Performance and Query Optimization


– RAISE_ERROR
– REPEAT
– REPLACE
– ROUND_TIMESTAMP
– SOUNDEX
– TIMESTAMP_FORMAT
– TIMESTAMPDIFF
– TRUNC_TIMESTAMP
– VARCHAR_FORMAT
– WEEK_ISO
It is recommended that the MQT only contain references to columns and column functions. In many
environments, queries that contain constants have the constants converted to parameter markers. This
conversion allows a much higher degree of ODP reuse. The MQT matching algorithm attempts to match
constants in the MQT with parameter markers or host variable values in the query. However, in some
complex cases this support is limited and could result in the MQT not matching the query.
Related concepts
Query dispatcher
The function of the dispatcher is to route the query request to either CQE or SQE, depending on the
attributes of the query. All queries are processed by the dispatcher. It cannot be bypassed.
Related reference
Details on the MQT matching algorithm
What follows is a generalized discussion of how the MQT matching algorithm works.

Using MQTs during query optimization


Before using MQTs, you need to consider your environment attributes.
To even consider using MQTs during optimization the following environmental attributes must be true:
• The query must specify ALWCPYDTA(*OPTMIZE) or INSENSITIVE cursor.
• The query must not be a SENSITIVE cursor.
• The table to be replaced with an MQT must not be update or delete capable for this query.
• The MQT currently has the ENABLE QUERY OPTIMIZATION attribute active
• The MATERIALIZED_QUERY_TABLE_USAGE QAQQINI option must be set to *ALL or *USER to enable use
of MQTs. The default setting of MATERIALIZED_QUERY_TABLE_USAGE does not allow usage of MQTs.
• The timestamp of the last REFRESH TABLE for an MQT is within the duration specified by
the MATERIALIZED_QUERY_TABLE_REFRESH_AGE QAQQINI option. Or *ANY is specified, which
allows MQTs to be considered regardless of the last REFRESH TABLE. The default setting of
MATERIALIZED_QUERY_TABLE_REFRESH_AGE does not allow usage of MQTs.
• The query must be run through SQE.
• The following QAQQINI options must match: IGNORE_LIKE_REDUNDANT_SHIFTS, NORMALIZE_DATA,
and VARIABLE_LENGTH_OPTIMIZATION. These options are stored at CREATE materialized query table
time and must match the options specified at query run time.
• The commit level of the MQT must be greater than or equal to the query commit level. The commit level
of the MQT is either specified in the MQT query using the WITH clause. Or it is defaulted to the commit
level that the MQT was run under when it was created.
• The field procedure encoded comparison (QAQQINI FIELDPROC_ENCODED_COMPARISON option) level
of the MQT must be greater than or equal to the query specified field procedure encoded comparison
level.

Database performance and query optimization 91


MQT examples
The following are examples of using MQTs.

Example 1
The first example is a query that returns information about employees whose job is DESIGNER. The
original query:

SELECT D.deptname, D.location, E.firstnme, E.lastname, E.salary+E.comm+E.bonus as total_sal


FROM Department D, Employee E
WHERE D.deptno=E.workdept
AND E.job = 'DESIGNER'

Create a table, MQT1, that uses this query:

CREATE TABLE MQT1


AS (SELECT D.deptname, D.location, E.firstnme, E.lastname, E.salary, E.comm, E.bonus,
E.job
FROM Department D, Employee E
WHERE D.deptno=E.workdept)
DATA INITIALLY IMMEDIATE REFRESH DEFERRED
ENABLE QUERY OPTIMIZATION
MAINTAINED BY USER

Resulting new query after replacing the specified tables with the MQT.

SELECT M.deptname, M.location, M.firstnme, M.lastname, M.salary+M.comm+M.bonus as total_sal


FROM MQT1 M
WHERE M.job = 'DESIGNER'

In this query, the MQT matches part of the user query. The MQT is placed in the FROM
clause and replaces tables DEPARTMENT and EMPLOYEE. Any remaining selection not done by
the MQT query (M.job= 'DESIGNER') is done to remove the extra rows. The result expression,
M.salary+M.comm+M.bonus, is calculated. JOB must be in the select-list of the MQT so that the
additional selection can be performed.
Visual Explain diagram of the query when using the MQT:

92 IBM i: Performance and Query Optimization


Example 2
Get the total salary for all departments that are located in 'NY'. The original query:

SELECT D.deptname, sum(E.salary)


FROM DEPARTMENT D, EMPLOYEE E
WHERE D.deptno=E.workdept AND D.location = 'NY'
GROUP BY D.deptname

Create a table, MQT2, that uses this query:

CREATE TABLE MQT2


AS (SELECT D.deptname, D.location, sum(E.salary) as sum_sal
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.deptno=E.workdept
GROUP BY D.Deptname, D.location)
DATA INITIALLY IMMEDIATE REFRESH DEFERRED
ENABLE QUERY OPTIMIZATION
MAINTAINED BY USER

Resulting new query after replacing the specified tables with the MQT:

SELECT M.deptname, sum(M.sum_sal)


FROM MQT2 M
WHERE M.location = 'NY'
GROUP BY M.deptname

Since the MQT could potentially produce more groups than the original query, the final resulting query
must group again and SUM the results to return the correct answer. Also, the selection M.location='NY'
must be part of the new query.
Visual Explain diagram of the query when using the MQT:

Database performance and query optimization 93


Details on the MQT matching algorithm
What follows is a generalized discussion of how the MQT matching algorithm works.
The tables specified in the query and the MQT are examined. If the MQT and the query specify the same
tables, then the MQT can potentially be used and matching continues. If the MQT references tables not
referenced in the query, then the unreferenced table is examined to determine if it is a parent table in
referential integrity constraint. If the foreign key is non-nullable and the two tables are joined using a
primary key or foreign key equal predicate, then the MQT can still be potentially used.

Example 3
The MQT contains fewer tables than the query:

SELECT D.deptname, p.projname, sum(E.salary)


FROM DEPARTMENT D, EMPLOYEE E, EMPPROJACT EP, PROJECT P
WHERE D.deptno=E.workdept AND E.Empno=ep.empno
AND ep.projno=p.projno
GROUP BY D.DEPTNAME, p.projname

Create an MQT based on the preceding query:

CREATE TABLE MQT3


AS (SELECT D.deptname, sum(E.salary) as sum_sal, e.workdept, e.empno
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.deptno=E.workdept
GROUP BY D.Deptname, e.workdept, e.empno)
DATA INITIALLY IMMEDIATE REFRESH DEFERRED
ENABLE QUERY OPTIMIZATION
MAINTAINED BY USER

The rewritten query:

SELECT M.deptname, p.projname, SUM(M.sum_sal)


FROM MQT3 M, EMPPROJACT EP, PROJECT P

94 IBM i: Performance and Query Optimization


WHERE M.Empno=ep.empno AND ep.projno=p.projno
GROUP BY M.deptname, p.projname

All predicates specified in the MQT, must also be specified in the query. The query could contain
additional predicates. Predicates specified in the MQT must match exactly the predicates in the query.
Any additional predicates specified in the query, but not in the MQT must be able to be derived from
columns projected from the MQT. See previous example 1.

Example 4
Set the total salary for all departments that are located in 'NY'.

SELECT D.deptname, sum(E.salary)


FROM DEPARTMENT D, EMPLOYEE E
WHERE D.deptno=E.workdept AND D.location = ?
GROUP BY D.Deptname

Create an MQT based on the preceding query:

CREATE TABLE MQT4


AS (SELECT D.deptname, D.location, sum(E.salary) as sum_sal
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.deptno=E.workdept AND D.location = 'NY'
GROUP BY D.deptnamet, D.location)
DATA INITIALLY IMMEDIATE REFRESH DEFERRED
ENABLE QUERY OPTIMIZATION
MAINTAINED BY USER

In this example, the constant 'NY' was replaced by a parameter marker and the MQT also had the
local selection of location='NY' applied to it when the MQT was populated. The MQT matching algorithm
matches the parameter marker and to the constant 'NY' in the predicate D.Location=?. It verifies that the
values of the parameter marker are the same as the constant in the MQT; therefore the MQT can be used.
The MQT matching algorithm also attempts to match where the predicates between the MQT and the
query are not the same. For example, if the MQT has a predicate SALARY > 50000, and the query has the
predicate SALARY > 70000, the MQT contains the rows necessary to run the query. The MQT is used in the
query, but the predicate SALARY > 70000 is left as selection in the query, so SALARY must be a column of
the MQT.

Example 5
SELECT D.deptname, sum(E.salary)
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.deptno=E.workdept AND D.location = 'NY'
GROUP BY D.deptname

Create an MQT based on the preceding query:

CREATE TABLE MQT5


AS (SELECT D.deptname, E.salary
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.deptno=E.workdept)
DATA INITIALLY IMMEDIATE REFRESH DEFERRED
ENABLE QUERY OPTIMIZATION
MAINTAINED BY USER

In this example, since D.Location is not a column of the MQT, the user query local selection predicate
Location='NY' cannot be determined, so the MQT cannot be used.

Example 6
SELECT D.deptname, sum(E.salary)
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.deptno=E.workdept
GROUP BY D.deptname

Database performance and query optimization 95


Create an MQT based on the preceding query:

CREATE TABLE MQT6(workdept, sumSalary)


AS (SELECT workdept, sum(salary)
FROM EMPLOYEE
GROUP BY workdept )
DATA INITIALLY IMMEDIATE REFRESH DEFERRED
ENABLE QUERY OPTIMIZATION
MAINTAINED BY USER

In this example, the SUM(salary) aggregation is pushed down through the join to the EMPLOYEE table,
allowing for a match and substitution of MQT6. A regrouping to (sum(sum(salary))) is defined at the top of
the query to compensate for the grouping pushdown.
Instead of department joining to all the rows in the employee table, it now has the opportunity to join to
the predetermined aggregates in MQT6. This type of MQT substitution can result in significant reduction of
processing and IO.
If the MQT contains grouping, then the query must be a grouping query. The simplest case is where the
MQT and the query specify the same list of grouping columns and column functions.
In some cases, if the MQT specifies group by columns that are a superset of query group by columns,
the query can be rewritten to do regrouping. This regrouping reaggregates the groups of the MQT into the
groups required by the query. When regrouping is required, the column functions need to be recomputed.
The following table shows the supported regroup expressions.
The regrouping expression/aggregation rules are:

Table 32. Expression/aggregation rules for MQTs


Query MQT Final query
COUNT(*) COUNT(*) as cnt SUM(cnt)
COUNT(*) COUNT(C2) as cnt2 (where c2 is SUM(cnt2)
non-nullable)
COUNT(c1) COUNT(c1) as cnt SUM(cnt)
COUNT(C1) (where C1 is non- COUNT(C2) as cnt2 (where C2 is SUM(cnt2)
nullable) non-nullable)
COUNT(distinct C1) C1 as group_c1 (where C1 is a COUNT(group_C1)
grouping column)
COUNT(distinct C1) where C1 is not a grouping MQT not usable
column
COUNT(C2) where C2 is from a COUNT(*) as cnt cnt*COUNT(C2)
table not in the MQT
COUNT(distinct C2) where C2 is Not applicable COUNT(distinct C2)
from a table not in the MQT
SUM(C1) SUM(C1) as sm SUM(sm)
SUM(C1) C1 as group_c1, COUNT(*) as cnt SUM(group_c1 * cnt)
(where C1 is a grouping column)
SUM(C2) where C2 is from a table COUNT(*) as cnt cnt*SUM(C2)
not in the MQT
SUM(distinct C1) C1 as group_c1 (where C1 is a SUM(group_C1)
grouping column)
SUM(distinct C1) where C1 is not a grouping MQT not usable
column

96 IBM i: Performance and Query Optimization


Table 32. Expression/aggregation rules for MQTs (continued)
Query MQT Final query
SUM(distinct C2) where C2 is Not applicable SUM(distinct C2)
from a table not in the MQT
MAX(C1) MAX(C1) as mx MAX(mx)
MAX(C1) C1 as group_C1 (where C1 is a MAX(group_c1)
grouping column)
MAX(C2) where C2 is from a table Not applicable MAX(C2)
not in the MQT
MIN(C1) MIN(C1) as mn MIN(mn)
MIN(C1) C1 as group_C1 (where C1 is a MIN(group_c1)
grouping column)
MIN(C2) where C2 is from a table Not applicable MIN(C2)
not in the MQT
GROUPING(C1) GROUPING(C1) as grp grp
GROUPING(C2) where C2 is from Not applicable GROUPING(C2)
a table not in the MQT

MQT matching does not support ARRAY_AGG, XMLAGG, and XMLGROUP grouping functions. AVG,
STDDEV, STDDEV_SAMP, VARIANCE_SAMPand VAR_POP are calculated using combinations of COUNT
and SUM. If AVG, STDDEV, or VAR_POP are included in the MQT and regroup requires recalculation of
these functions, the MQT cannot be used. It is recommended that the MQT only use COUNT, SUM, MIN,
and MAX. If the query contains AVG, STDDEV, or VAR_POP, it can be recalculated using COUNT and SUM.
If FETCH FIRST N ROWS is specified in the MQT, then FETCH FIRST N ROWS must also be specified in
the query. Also, the number of rows specified for the MQT must be greater than or equal to the number of
rows specified in the query. It is not recommended that an MQT contain the FETCH FIRST N ROWS clause.
The ORDER BY clause on the MQT can be used to order the data in the MQT if a REFRESH TABLE is run. It
is ignored during MQT matching and if the query contains an ORDER BY clause, it is part of the rewritten
query.
Related reference
MQT supported function
Although an MQT can contain almost any query, the optimizer only supports a limited set of query
functions when matching MQTs to user specified queries. The user-specified query and the MQT query
must both be supported by the SQE optimizer.

Determining unnecessary MQTs


You can easily determine which MQTs are being used for query optimization. However, you can now easily
find all MQTs and retrieve statistics on MQT usage as a result of System i Navigator and IBM i functionality.
To assist you in tuning your performance, this function produces statistics on MQT usage in a query.
To access through the System i Navigator, navigate to: Database > Schemas > Tables. Right-click your
table and select Show Materialized Query Tables. You can also view MQT usage information by right-
click on Tables or Views folder and select Show Materialized Query Tables. This action displays usage
information for MQTs created over all the tables or view in that schema.
Note: You can also view the statistics through an application programming interface (API).
In addition to all existing attributes of an MQT, two fields can help you determine unnecessary MQTs.
These fields are:

Database performance and query optimization 97


Last Query Use States the timestamp when the MQT was last used by the optimizer to replace user
specified tables in a query.
Query Use Count Lists the number of instances the MQT was used by the optimizer to replace user
specified tables in a query.

The fields start and stop counting based on your situation, or the actions you are currently performing on
your system. A save and restore procedure does not reset the statistics counter if the MQT is restored
over an existing MQT. If an MQT is restored that does not exist on the system, the statistics are reset.
Related information
Retrieve member description (QUSRMBRD) command

Summary of MQT query recommendations


Follow these recommendations when using MQT queries.
• Do not include local selection or constants in the MQT because that limits the number of user-specified
queries where the optimizer can use the MQT.
• For grouping MQTs, only use the SUM, COUNT, MIN, and MAX grouping functions. The query optimizer
can recalculate AVG, STDDEV, and VAR_POP in user specified queries.
• Specifying FETCH FIRST N ROWS in the MQT limits the number of user-specified queries where the
query optimizer can use the MQT. Not recommended.
• If the MQT is created with DATA INITIALLY DEFERRED, consider specifying DISABLE QUERY
OPTIMIZATION to prevent the optimizer from using the MQT until it has been populated. When the
MQT is populated and ready for use, the ALTER TABLE statement with ENABLE QUERY OPTIMIZATION
enables the MQT.
In addition, consider using a sparse index or EVI INCLUDE additional aggregates rather than an MQT if you
are concerned with stale data.
MQT tables need to be optimized just like non-MQT tables. It is recommended that indexes are created
over the MQT columns used for selection, join, and grouping, as appropriate. Column statistics are
collected for MQT tables.
The database monitor shows the list of MQTs considered during optimization. This information is in the
3030 record. If MQTs have been enabled through the QAQQINI file, and an MQT exists over at least one of
the tables in the query, there is a 3030 record for the query. Each MQT has a reason code indicating that it
was used or if it was not used, why it was not used.
Related concepts
How the EVI works
EVIs work in different ways for costing and implementation.
Related reference
Sparse index optimization
An SQL sparse index is like a select/omit access path. Both the sparse index and the select/omit logical
file contain only keys that meet the selection specified. For a sparse index, the selection is specified
with a WHERE clause. For a select/omit logical file, the selection is specified in the DDS using the COMP
operation.

Recursive query optimization


Certain applications and data are recursive by nature. Examples of such applications are a bill-of-material,
reservation, trip planner, or networking planning system. Data in one results row has a natural relationship
(call it a parent, child relationship) with data in another row or rows. The kinds of recursion implemented
in these systems can be performed by using SQL Stored Procedures and temporary results tables.
However, the use of a recursive query to facilitate the access of this hierarchical data can lead to a
more elegant and better performing application.

98 IBM i: Performance and Query Optimization


Recursive queries can be implemented by defining either a Recursive Common Table Expression (RCTE)
or a Recursive View.

Recursive query example


A recursive query is one that is defined by a Union All with an initialization fullselect that seeds the
recursion. The iterative fullselect contains a direct reference to itself in the FROM clause.
There are additional restrictions as to what can be specified in the definition of a recursive query. Those
restrictions can be found in SQL Programming topic.
Functions like grouping, aggregation, or distinct require a materialization of all the qualifying records
before performing the function. These functions cannot be allowed within the iterative fullselect itself.
The functions must be placed in the main query, allowing the recursion to complete.
The following is an example of a recursive query over a table called flights, that contains information
about departure and arrival cities. The query returns all the flight destinations available by recursion from
the two specified cities (New York and Chicago). It also returns the number of connections and total cost
to arrive at that final destination.
This example uses the recursion process to also accumulate information like the running cost and number
of connections. Four values are put in the queue entry. These values are:
• The originating departure city (either Chicago or New York) because it remains fixed from the start of the
recursion
• The arrival city which is used for subsequent joins
• The incrementing connection count
• The accumulating total cost to reach each destination
Typically the data needed for the queue entry is less than the full record (sometimes much less) although
that is not the case for this example.

CREATE TABLE flights


(
departure CHAR (10) NOT NULL WITH DEFAULT,
arrival CHAR (10) NOT NULL WITH DEFAULT,
carrier CHAR (15) NOT NULL WITH DEFAULT,
flight_num CHAR (5) NOT NULL WITH DEFAULT,
ticket INT NOT NULL WITH DEFAULT)

WITH destinations (departure, arrival, connects, cost ) AS


(
SELECT f.departure,f.arrival, 0, ticket
FROM flights f
WHERE f.departure = 'Chicago' OR
f.departure = 'New York'
UNION ALL
SELECT
r.departure, b.arrival, r.connects + 1,
r.cost + b.ticket
FROM destinations r, flights b
WHERE r.arrival = b.departure
)
SELECT DISTINCT departure, arrival, connects, cost
FROM destinations

The following is the initialization fullselect of the preceding query. It seeds the rows that start the
recursion process. It provides the initial destinations (arrival cities) that are a direct flight from Chicago or
New York.

SELECT f.departure,f.arrival, 0, ticket


FROM flights f
WHERE f.departure='Chicago' OR
f.departure='New York'

The following is the iterative fullselect of the preceding query. It contains a single reference in the FROM
clause to the destination recursive common table expression. It also sources further recursive joins to

Database performance and query optimization 99


the same flights table. The arrival values of the parent row (initially direct flights from New York or
Chicago) are joined with the departure value of the subsequent child rows. It is important to identify the
correct parent/child relationship on the recursive join predicate or infinite recursion can occur. Other local
predicates can also be used to limit the recursion. For example, for a limit of at most 3 connecting flights,
a local predicate using the accumulating connection count, r.connects<=3, can be specified.

SELECT
r.departure, b.arrival, r.connects + 1 ,
r.cost + b.ticket
FROM destinations r, flights b
WHERE r.arrival=b.departure

The main query is the query that references the recursive common table expression or view. It is in the
main query where requests like grouping, ordering, and distinct are specified.

SELECT DISTINCT departure, arrival, connects, cost


FROM destinations

Implementation considerations
To implement a source for the recursion, a new temporary data object is provided called a queue. As rows
meet the requirements of either the initialization fullselect or the iterative fullselect, they are pulled up
through the union all. Values necessary to feed the continuing recursion process are captured and placed
in an entry on the queue: an enqueue operation.
At query runtime, the queue data source then takes the place of the recursive reference in the common
table expression or view. The iterative fullselect processing ends when the queue is exhausted of entries
or a fetch N rows limitation has been met. The recursive queue feeds the recursion process and holds
transient data. The join between dequeuing of these queue entries and the rest of the fullselect tables is
always a constrained join, with the queue on the left.

100 IBM i: Performance and Query Optimization


Multiple initialization and iterative fullselects
The use of multiple initialization and iterative fullselects specified in the recursive query definition allows
for a multitude of data sources and separate selection requirements to feed the recursion process.
For example, the following query allows for final destinations accessible from Chicago by both flight and
train travel.

WITH destinations (departure, arrival, connects, cost ) AS


(
SELECT f.departure, f.arrival, 0 , ticket
FROM flights f
WHERE f.departure='Chicago'
UNION ALL
SELECT t.departure, t.arrival, 0 , ticket
FROM trains t
WHERE t.departure='Chicago'

Database performance and query optimization 101


UNION ALL
SELECT
r.departure,b.arrival, r.connects + 1 ,
r.cost + b.ticket
FROM destinations r, flights b
WHERE r.arrival=b.departure
UNION ALL
SELECT
r.departure,b.arrival, r.connects+1 ,
r.cost+b.ticket
FROM destinations r, trains b
WHERE r.arrival=b.departure)

SELECT departure, arrival, connects,cost


FROM destinations;

All rows coming out of the RCTE/View are part of the recursion process and need to be fed back in. When
there are multiple fullselects referencing the common table expression, the query is rewritten by the
optimizer to process all non-recursive initialization fullselects first. Then, using a single queue feed, those
same rows and all other row results are sent equally to the remaining iterative fullselects. No matter how
you order the initialization and iterative fullselects in the definition of the RCTE/view, the initialization
fullselects run first. The iterative fullselects share equal access to the contents of the queue.

102 IBM i: Performance and Query Optimization


Predicate pushing
When processing most queries with non-recursive common table expressions or views, local predicates
specified on the main query are pushed down so fewer records need to be materialized. Pushing local
predicates from the main query into the defined recursive part of the query (through the Union ALL),
however, could considerably alter the process of recursion itself. So as a rule, the Union All specified in a
recursive query is currently a predicate fence. Predicates are not pushed down or up, through this fence.
The following is an example of how pushing a predicate in to the recursion limits the recursive results and
alter the intent of the query.
The intent of the query is to find all destinations accessible from 'Chicago', not including the final
destination of 'Dallas'. Pushing the "arrival<>'Dallas'" predicate into the recursive query alters the output
of the intended results. It prevents the output of final destinations where 'Dallas' was an intermediate
stop.

WITH destinations (departure, arrival, connects, cost ) AS


(
SELECT f.departure,f.arrival, 0, ticket
FROM flights f
WHERE f.departure='Chicago'
UNION ALL
SELECT
r.departure, b.arrival, r.connects + 1 ,
r.cost + b.ticket
FROM destinations r, flights b
WHERE r.arrival=b.departure
)
SELECT departure, arrival, connects, cost
FROM destinations
WHERE arrival != 'Dallas'

Conversely, the following is an example where a local predicate applied to all the recursive results is a
good predicate to put in the body of the recursive definition because it could greatly decrease the number
of rows materialized from the RCTE/View. The better query request here is to specify the r.connects <=3
local predicate with in the RCTE definition, in the iterative fullselect.

WITH destinations (departure, arrival, connects, cost ) AS


(
SELECT f.departure,f.arrival, 0, ticket
FROM flights f
WHERE f.departure='Chicago' OR
f.departure='New York'
UNION ALL
SELECT
r.departure, b.arrival, r.connects + 1 ,
r.cost + b.ticket
FROM destinations r, flights b
WHERE r.arrival=b.departure
)
SELECT departure, arrival, connects, cost
FROM destinations
WHERE r.connects<=3

Placement of local predicates is key in recursive queries. They can incorrectly alter the recursive results
if pushed into a recursive definition. Or they can cause unnecessary rows to be materialized and then
rejected, when a local predicate could legitimately help limit the recursion.

Specifying SEARCH consideration


Certain applications dealing with hierarchical, recursive data could have a requirement in how data is
processed: by depth or by breadth.
Using a queuing (First In First Out) mechanism to track the recursive join key values implies the results
are retrieved in breadth first order. Breadth first means retrieving all the direct children of a parent
row before retrieving any of the grandchildren of that same row. This retrieval is an implementation
distinction, however, and not a guarantee.

Database performance and query optimization 103


Applications might want to guarantee how the data is retrieved. Some applications might want to retrieve
the hierarchical data in depth first order. Depth first means that all the descendents of each immediate
child row are retrieved before the descendents of the next child are retrieved.
The SQL architecture allows for the guaranteed specification of how the application retrieves the resulting
data by the use of the SEARCH DEPTH FIRST or BREADTH FIRST keyword. When this option is specified,
name the recursive join value, identify a set sequence column, and provide the sequence column in an
outer ORDER BY clause. The results are output in depth or breadth first order. Note this ordering is
ultimately a relationship sort and not a value-based sort.
Here is the preceding example output in depth first order.

WITH destinations (departure, arrival, connects, cost ) AS


(
SELECT f.departure, f.arrival, 0 , ticket
FROM flights f
WHERE f.departure='Chicago' OR f.departure='New York'
UNION ALL
SELECT
r.departure,b.arrival, r.connects+1 ,
r.cost+b.ticket
FROM destinations r, flights b
WHERE r.arrival=b.departure)

SEARCH DEPTH FIRST BY arrival SET depth_sequence

SELECT *
FROM destinations
ORDER BY depth_sequence

If the ORDER BY clause is not specified in the main query, the sequencing option is ignored. To facilitate
the correct sort there is additional information put on the queue entry during recursion. With BREADTH
FIRST, it is the recursion level number and the immediate ancestor join value, so sibling rows can
be sorted together. A depth first search is a little more data intensive. With DEPTH FIRST, the query
engine needs to represent the entire ancestry of join values leading up to the current row and put that
information in a queue entry. Also, because these sort values are not coming from an external data
source, the sort implementation is always a temporary sorted list (no indexes possible).
Do not use the SEARCH option if you do not need your data materialized in a depth or breadth first
manner. There is additional CPU and memory overhead to manage the sequencing information.

Specifying CYCLE considerations


Recognizing that data in the tables used in a recursive query might be cyclic in nature is important to
preventing infinite loops.
The SQL architecture allows for the optional checking for cyclic data and discontinuing the repeating
cycles at that point. This additional checking is done by the use of the CYCLE option. The correct join
recursion value must be specified on the CYCLE request and a cyclic indicator must be specified. The
cyclic indicator could be optionally output in the main query and can be used to help determine and
correct errant cyclic data.

WITH destinations (departure, arrival, connects, cost , itinerary) AS


(
SELECT f.departure, f.arrival, 1 , ticket, CAST(f.departure||f.arrival AS VARCHAR(2000))
FROM flights f
WHERE f.departure='New York'
UNION ALL
SELECT r.departure,b.arrival, r.connects+1 ,
r.cost+b.ticket, cast(r.itinerary||b.arrival AS varchar(2000))
FROM destinations r, flights b
WHERE r.arrival = b.departure)
CYCLE arrival SET cyclic TO '1' DEFAULT '0' USING Cycle_Path

SELECT departure, arrival, itinerary, cyclic


FROM destinations

When a cycle is determined to be repeating, the output of that cyclic sequence of rows is stopped. To
check for a 'repeated' value however, the query engine needs to represent the entire ancestry of the join

104 IBM i: Performance and Query Optimization


values leading up to the current row in order to look for the repeating join value. This ancestral history is
information that is appended to with each recursive cycle and put in a field on the queue entry.
To implement this history field, the query engine uses a compressed representation of the recursion
values on the ancestry chain. The query engine can then do a fixed length, quicker scan through the
accumulating ancestry to determine if the value has been seen before. This compressed representation is
determined by the use of a distinct node in the query tree.
Do not use the CYCLE option unless you know your data is cyclic, or you want to use it specifically to help
find the cycles for correction or verification purposes. There is additional CPU and memory overhead to
manage and check for repeating cycles before a given row is materialized.

SMP and recursive queries


Recursive queries can benefit as much from symmetric multiprocessing (SMP) as do other queries on the
system.
Recursive queries and parallelism, however, present some unique requirements. The initialization
fullselect of a recursive query is the fullselect that seeds the initial values of the recursion. It is likely
to produce only a small fraction of the ultimate results that cycle through the recursion process. The

Database performance and query optimization 105


query optimizer does not want each of the threads running in parallel to have a unique queue object that
feeds only itself. This results in some threads having way too much work to do and others threads quickly
depleting their work.
The best way to handle this work is to have all the threads share the same queue. This method allows a
thread to enqueue a new recursive key value just as a waiting thread is there to dequeue that request. A
shared queue allows all threads to actively contribute to the overall depletion of the queue entries until no
thread is able to contribute more results.
Having multiple threads share the same queue, however, requires some management by the Query
runtime so that threads do not prematurely end. Some buffering of the initial seed values might be
necessary. This buffering is illustrated in the following query, where there are two fullselects that seed the
recursion. A buffer is provided so that no thread hits a dequeue state and terminates before the query has
seeded enough recursive values to get things going.
The following Visual Explain diagram shows the plan for the following query run with CHGQRYA
DEGREE(*NBRTASKS 4). It shows how the results of the multiple initialization fullselects are buffered
up. The multiple threads, illustrated by the multiple arrow lines, are acting on the enqueue and dequeue
request nodes. As with all SMP queries, the multiple threads, in this case 4, put their results into a
Temporary List object which becomes the output for the main query.

cl:chgqrya degree(*nbrtasks 4);

WITH destinations (departure, arrival, connects, cost )AS


(
SELECT f.departure, f.arrival, 0 , ticket
FROM flights f WHERE f.departure='Chicago'
UNION ALL
SELECT t.departure, t.arrival, 0 , ticket
FROM trains t WHERE t.departure='Chicago'
UNION ALL
SELECT
r.departure,b.arrival, r.connects+1 ,
r.cost+b.ticket
FROM destinations r, flights b
WHERE r.arrival=b.departure
UNION ALL
SELECT
r.departure,b.arrival, r.connects+1 ,
r.cost+b.ticket
FROM destinations r, trains b
WHERE r.arrival=b.departure)
SELECT departure, arrival, connects,cost
FROM destinations;

106 IBM i: Performance and Query Optimization


Database performance and query optimization 107
System-period temporal tables
Querying a system-period temporal table can return results for a specified point or period in time. These
results can include both current values and previous historic values. The following sample queries request
policy information from a system-period temporal table (policy_info), which also implicitly get information
from the associated history table (hist_policy_info). See the “Querying system-period temporal data”
topic in the Database Administration book for the layout of these tables and more information on how to
specify time criteria for a system-period temporal table in a query.

Query with FOR SYSTEM_TIME AS OF specified.


SELECT policy_id, coverage
FROM policy_info
FOR SYSTEM_TIME AS OF '2011-02-28-09.10.12.649592000000'

For this query, the begin column of the period is inclusive, while the end column is exclusive. The history
table row(s) with the begin column value less than or equal to '2011-02-28-09.10.12.649592000000'
and the end column value greater than '2011-02-28-09.10.12.649592000000' will be included in the
result.
As a result Db2 rewrites the query as follows:

SELECT policy_id, coverage FROM


(SELECT policy_id, coverage
FROM policy_info
WHERE sys_start <= '2011-02-28-09.10.12.649592000000'
UNION ALL
SELECT policy_id, coverage
FROM hist_policy_info
WHERE sys_start <= '2011-02-28-09.10.12.649592000000'
AND sys_end > '2011-02-28-09.10.12.649592000000')

Query with FOR SYSTEM_TIME FROM…TO specified.


SELECT policy_id, coverage, sys_start, sys_end
FROM policy_info
FOR SYSTEM_TIME FROM '0001-01-01-00.00.00.000000'
TO '9999-12-30-00.00.00.000000000000'
WHERE policy_id = 'C567'

For this query, the begin column and end column of the period are exclusive. The history table row(s)
with the begin column value less than '9999-12-30-00.00.00.000000000000' and the end column value
greater than '0001-01-01-00.00.00.000000' will be included in the result.
As a result, Db2 rewrites the query as follows:

SELECT policy_id, coverage, sys_start, sys_end FROM


(SELECT policy_id, coverage, sys_start, sys_end
FROM policy_info
WHERE sys_start < '9999-12-30-00.00.00.000000000000'
AND TIMESTAMP('0001-01-01-00.00.00.000000') <
TIMESTAMP('9999-12-30-00.00.00.000000000000')
UNION ALL
SELECT policy_id, coverage, sys_start, sys_end
FROM hist_policy_info
WHERE sys_start < '9999-12-30-00.00.00.000000000000'
AND sys_end > '0001-01-01-00.00.00.000000')
AND TIMESTAMP('0001-01-01-00.00.00.000000') <
TIMESTAMP('9999-12-30-00.00.00.000000000000')
WHERE policy_id = 'C567'

Query with FOR SYSTEM_TIME BETWEEN…AND specified.


SELECT policy_id, coverage
FROM policy_info

108 IBM i: Performance and Query Optimization


FOR SYSTEM_TIME BETWEEN '2011-02-28-09.10.12.649592000000'
AND '9999-12-30-00.00.00.000000000000'

For this query, the begin column of the period is inclusive, while the end column is exclusive. The history
table row(s) with the begin column value less than or equal to '9999-12-30-00.00.00.000000000000'
and the end column value greater than '2011-02-28-09.10.12.649592000000' will be included in the
result.
As a result, Db2 rewrites the query as follows:

SELECT policy_id, coverage, sys_start, sys_end FROM


(SELECT policy_id, coverage, sys_start, sys_end
FROM policy_info
WHERE sys_start <= '9999-12-30-00.00.00.000000000000'
AND TIMESTAMP('2011-02-28-09.10.12.649592000000') <=
TIMESTAMP('9999-12-30-00.00.00.000000000000')
UNION ALL
SELECT policy_id, coverage, sys_start, sys_end
FROM hist_policy_info
WHERE sys_start <= '9999-12-30-00.00.00.000000000000'
AND sys_end > '2011-02-28-09.10.12.649592000000')
AND TIMESTAMP('2011-02-28-09.10.12.649592000000') <=
TIMESTAMP('9999-12-30-00.00.00.000000000000')

Query with time criteria specified via CURRENT TEMPORAL SYSTEM_TIME special
register.
The advantage of using this method is that you can change the time criteria later and not have to modify
the SQL. For example, assume that you want to retrieve data from policy_info for a given policy_id of C567
that is from one year ago. If the SYSTIME option is set to YES, you can set the CURRENT TEMPORAL
SYSTEM_TIME special register and issue the SELECT statement as follows:

SET CURRENT TEMPORAL SYSTEM_TIME = CURRENT TIMESTAMP – 1 YEAR;

SELECT policy_id, coverage FROM policy_info


WHERE policy_id = 'C567';

Db2 interprets the SELECT statement as follows:

SELECT policy_id, coverage FROM policy_info


FOR SYSTEM_TIME AS OF CURRENT TEMPORAL SYSTEM_TIME
WHERE policy_id = 'C567';

For this query, the begin column of the period is inclusive, while the end column is exclusive. The history
table row(s) with the begin column value less than or equal to CURRENT TEMPORAL SYSTEM_TIME and
the end column value greater than CURRENT TEMPORAL SYSTEM_TIME will be included in the result.
As a result, Db2 rewrites the query as follows:

SELECT policy_id, coverage FROM


(SELECT policy_id, coverage
FROM policy_info
WHERE sys_start <= CURRENT TEMPORAL SYSTEM_TIME
UNION ALL
SELECT policy_id, coverage
FROM hist_policy_info
WHERE sys_start <= CURRENT TEMPORAL SYSTEM_TIME
AND sys_end > CURRENT TEMPORAL SYSTEM_TIME)
WHERE policy_id = 'C567';

Adaptive Query Processing


Adaptive Query Processing analyzes actual query run time statistics and uses that information for
subsequent optimizations.
With rapidly increasing amounts of data, the price of miscalculating complex plans can result in dramatic
performance problems. These problems might be measured in minutes or hours instead of seconds
or minutes. Traditionally, optimizer architecture has attempted to overcome potential plan problems in

Database performance and query optimization 109


several ways. The most common technique is to increase the amount of time spent optimizing a query,
searching for safe alternatives. While additional time reduces the likelihood of a failed plan, it does not
fundamentally avoid the problem.
The Db2 optimizer relies on statistical estimates to optimize a query. These estimates can be inaccurate
for a number of reasons. The reasons include a lack of statistical metadata for the query tables, complex
join conditions, skewed or rapidly changing data within the tables, and others.
The SQE query engine uses a technique called Adaptive Query Processing (AQP). AQP analyzes actual
query run time statistics and uses that information to correct previous estimates. These updated
estimates can provide better information for subsequent optimizations.
Related reference
Adaptive Query Processing in Visual Explain
You can use Visual Explain to request a new plan.

How AQP works


There are three main parts to AQP support.
• Global Statistics Cache (GSC): The “Global Statistics Cache” on page 16 is a system-side repository
of statistical information gathered from actual query runs. When the SQE query engine observes a
discrepancy between record count estimates and actual observed values, an entry might be made in
the GSC. This entry provides the optimizer with more accurate statistical information for subsequent
optimizations.
• AQP Request Support: This support runs after a query completes. The processing is done in a system
task so it does not affect the performance of user applications. Estimated record counts are compared
to the actual values. If significant discrepancies are noted, the AQP Request Support stores the
observed statistic in the GSC. The AQP Request Support might also make specific recommendations
for improving the query plan the next time the query runs.
• AQP Handler: The AQP Handler runs in a thread parallel to a running query and observes its progress.
The AQP handler wakes up after a query runs for at least 2 seconds without returning any rows. Its job
is to analyze the actual statistics from the partial query run, diagnose, and possibly recover from join
order problems. These join order problems are due to inaccurate statistical estimates.
The query can be reoptimized using partial observed statistics or specific join order recommendations
or both. If this optimization results in a new plan, the old plan is terminated and the query restarted with
the new plan, provided the query has not returned any results.
AQP looks for an unexpected starvation join condition when it analyzes join performance. Starvation join is
a condition where a table late in the join order eliminates many records from the result set. In general, the
query would perform better if the table that eliminates the large number of rows is first in the join order.
When AQP identifies a table that causes an unexpected starvation join condition, the table is noted as the
'forced primary table'. The forced primary table is saved for a subsequent optimization of the query.
That subsequent optimization with the forced primary recommendation can be used in two ways:
• The forced primary table is placed first in the join order, overriding the join order implied by the
statistical estimates. The rest of the join order is defined using existing techniques.
• The forced primary table can be used for LPG preselection against a large fact table in the join.
Related reference
Adaptive Query Processing in Visual Explain
You can use Visual Explain to request a new plan.

AQP example
Here is an example query with an explanation of how AQP could work.

SELECT * from t1, t2, t3, t4


WHERE t1.c1=t2.c1 AND t1.c2=t3.c2
AND t1.c3 = CURRENT DATE - t4.c3

110 IBM i: Performance and Query Optimization


AND t1.c5 < 50 AND t2.c6 > 40
AND t3.c7 < 100 AND t4.c8 - t4.c9 < 5

The WHERE clause of the preceding query contains a predicate, t1.c3 = CURRENT DATE - t4.c3,
that is difficult to estimate. The estimation difficulty is due to the derivation applied to column t4.c3
and the derivation involving columns t4.c8 and t4.c9. For the purposes of this example, the predicate
t1.c3 = CURRENT DATE - t4.c3 actually eliminates all or nearly all records in the join.
Due to characteristics of the columns involved in that predicate, the statistical estimate has many rows
returned from the join. The optimizer selects join order t1, t3, t2, t4 based on the following record
count estimates.
• Join t1 to t3 produces 33,000,000 rows.
• Join t1, t3 result to t2 produces 1,300,000 rows.
• Join t1, t3, t2 result to t4 (final result set) produces 5 million rows.
The join order is reasonable assuming that the final result set actually produces 5 million rows, but the
estimate is incorrect. The query performs poorly since tables t1, t3, t2 are joined first, producing
1,300,000 rows. These rows are all rejected by table t4 and the t1.c3 = CURRENT DATE - t4.c3
predicate (join starvation).
AQP identifies t4 as the forced primary table. The optimizer would choose t1 as the second table in the
join order since there are no join conditions between t4 and t2 or t3. Since the join condition between
tables t4 and t1 selects few rows, this plan is likely many orders of magnitude faster than the original
plan.
Related reference
Adaptive Query Processing in Visual Explain
You can use Visual Explain to request a new plan.

AQP join order


Adaptive Query Processing analyzes actual query run time join statistics and uses that information for
subsequent join optimizations.
The SQE engine implements AQP join order recommendations in the following ways:
Subsequent to run
When each query completes, a fast check is done on key points of the query execution to compare
actual selected records with the estimates. If there is a significant discrepancy, then a stand-alone task is
notified to do a deeper analysis of the query execution.
The query plan and the execution statistics are passed to the task. A separate task is used for the
in-depth analysis so the user job is not impacted while the deep analysis is done. Each step of the join is
analyzed, looking for characteristics of starvation join. Starvation join shows a significant reduction in the
number of rows produced compared to the previous step. The definition of what is considered significant
depends on a number of factors.
If the criteria for starvation join are met, the actual number of records selected at key points of the query
are compared to estimates. If there is a significant discrepancy between the actual and estimated record
counts, the table at that join position is identified as a 'forced primary table'. This table is saved with
the query plan in the system plan cache. When the query runs in the future, the optimizer retrieves the
original plan from the system plan cache. The optimizer sees the forced primary table recommendation,
and optimizes the query using this recommendation.
The forced primary recommendation is used in two ways by the optimizer:
• The forced primary table is placed first in the join order by the join order optimization strategy.
• The forced primary table is used by the strategy for LPG optimization. The preceding example is a star
join since table T1 is joined to the other tables in the query. t1.c3 is the column used to join T1 to T4. If
an index exists over this join column, then it might be advantageous to do preselection against table T1

Database performance and query optimization 111


using the records selected from table T4. The forced primary table recommendation is used as a hint for
the optimizer to consider this technique.
Concurrent to run
The preceding logic to identify starvation join can also run in a thread in parallel to the executing query.
The AQP handler thread is created for longer running queries. The thread monitors the query execution
and can run the same logic described earlier against partial data from the query execution.
If the partial results show starvation join and significant differences with the record count estimates,
the query is reoptimized in the thread. When the new plan is ready, the execution of the original plan
is stopped and the new plan started. This scheme for correcting join problems 'on the fly' can only be
carried out before any records are selected for the final result set.
Note: AQP can help correct query performance problems, but it is not a substitute for a good database
design coupled with a good indexing strategy.
Related reference
Adaptive Query Processing in Visual Explain
You can use Visual Explain to request a new plan.

Database Monitor additions for AQP


Additional information is logged in the database monitor when the AQP handler code replaces an
executing plan.
A new set of 30xx records is written to the database monitor reflecting the replaced plan. The user needs
to be able to distinguish between records produced for the first plan iteration and records produced for
subsequent optimization. To distinguish these records, an unused short integer column of the database
monitor record is used as a ‘plan iteration counter'.
Column QQSMINTF is used for this purpose. For the original optimization of the query, the 30xx records
have this field set to 1. Subsequent reoptimization done by AQP processing will increment the value by 1.
The following is an example of how DB monitor output might look like when a is replaced ‘on the fly'. The
example query is the following two-file join with an ORDER BY clause over one of the tables:

SELECT a.orderkey,b.orderkey
FROM rvdstar/item_fact3 a, rvdstar/item_fact b
WHERE a.quarter – 8 = b.quarter
ORDER BY b.orderkey

Assume that an order by pushdown plan is chosen, then replaced using AQP while the query is running.
The following is an example of what the DB monitor records might look like. The columns shown for the
purposes of explaining the changes are QQRID, QQUCNT, QQSMINTF, and QQRCOD. The other fields in
the monitor are not affected by AQP processing.

Table 33. Database monitor records for example query


QQRID QQUCNT QQSMINTF QQRCOD
3010 14 - -
3006 14 1 A0
3001 14 1 I2
3000 14 1 T1
3023 14 1 -
3007 14 1 -
3020 14 1 I1
3014 14 1 -

112 IBM i: Performance and Query Optimization


Table 33. Database monitor records for example query (continued)
QQRID QQUCNT QQSMINTF QQRCOD
5005 14 1 -
5002 14 1 -
5004 14 1 -
5007 14 1 -
3006 14 2 B6
3000 14 2 T1
3000 14 2 T3
3023 14 2 -
3003 14 2 F7
3007 14 2 -
3020 14 2 I1
3014 14 2 -
5005 14 2 -
5002 14 2 -
5004 14 2 -
1000 14 2 -
5007 14 2 -
3019 14 - -
1000 14 - -

Notes on the preceding table:


• There is a full set of optimizer-generated records that reflect the first choice of the optimizer: an order
by pushdown plan. These records have the QQSMINTF column value set to 1. There is a 3001 record
indicating an index was used to provide the ordering. There are 3000 and 3023 records indicating a
Table Scan of the second table and a temporary hash table built to aid join performance. The remaining
records, including the 3014 and the 500x records, have QQSMINTF set to 1 to reflect their association
with the original order by pushdown plan.
• There is a second full set of optimizer-generated records that reflect the second choice of the optimizer:
a sorted temporary plan to implement the ORDER BY. These records have the QQSMINTF column value
set to 2. This time there are two 3000 records indicating table scan was used to access both tables.
There is a 3023 record indicating a temporary hash table was built and a 3003 record indicating the
results were sorted. The remaining records, including the 3014 and the 500x records, have QQSMINTF
set to 2 to reflect their association with the replacement plan.
• Both sets of optimizer records have the same unique count (QQUCNT value).
• There is a 3006 (Access Plan Rebuilt) record generated for each replacement plan (QQSMINTF > 0).
The QQRCOD (reason code) value is set to a new value, ‘B6'. The ‘B6' value indicates the access plan
was rebuilt due to AQP processing. In the example, there is a 3006 record with QQSMINTF = 1 and
a QQRCOD value of ‘A0'. The 1 indicates that the original optimization built the plan for the first time.
There might not be a 3006 record associated with the original optimization if the optimizer was able to
reuse a plan from the plan cache.
• The 1000, 3010 and 3019 records are produced by XPF at open or close time. These records are not
generated by the optimizer so there are no changes due to AQP. There are one set of the records, as in

Database performance and query optimization 113


previous releases, regardless of whether AQP replaced the plan. The QQSMINTF value is NULL for these
records.
• The replacement plan is the plan that runs to completion and returns the results. To retrieve the
DB monitor records from the plan that actually returns the records, it is necessary to query the DB
monitor file using a subquery. Retrieve the records where the QQSMINTF value is equal to the maximum
QQSMINTF value for a given QQUCNT.
Related concepts
Database monitor formats
This section contains the formats used to create the database monitor SQL tables and views.
Related reference
Monitoring your queries using the Database Monitor
Start Database Monitor (STRDBMON) command gathers information about a query in real time and
stores this information in an output table. This information can help you determine whether your system
and your queries are performing well, or whether they need fine-tuning. Database monitors can generate
significant CPU and disk storage overhead when in use.
Adaptive Query Processing in Visual Explain
You can use Visual Explain to request a new plan.
QAQQINI query options
There are different options available for parameters in the QAQQINI file.

Row and column access control (RCAC)


Db2 for i introduces row and column access control (RCAC) as an additional layer of data security. RCAC
controls access to a table at the row level, column level, or both. RCAC can be used to complement the
existing table privileges model.

Indexing Strategy and RCAC


This section focuses on the consequence of RCAC to your SQL query performance when indexing is used.
Row and column access control (RCAC) places access control at the table level around the data itself. SQL
rules, which are known as row permissions or column masks, created on rows and columns are the basis
of the implementation of this capability.
You can use row and column access control to ensure that your users have access to only the data that
is required for their work. For example, tellers in a bank can access customer rows in the CUSTOMER
table only from their own branch. All tellers are members of the group user profile TELLER. Customer
service representative or telemarketers are members of other groups and allowed to see all rows. A row
permission is created by a user who is authorized to the QIBM_DB_SECADM function usage ID.
These SQL rules add additional predicates to any queries or data access requests over tables with
defined and activated RCAC permissions. In this example, SQL rules are added to queries over the
CUSTOMER table to enforce the following access rules. Depending on the nature of the rules, additional
indexes might be advised or existing indexes might need to be enhanced or altered to accommodate
the additional predicates enforcing the access. For example, when the TELLER_ROW_ACCESS permission
is enabled, additional index advise might include the BRANCH_INFO table and key EMP_ID. In this
particular example, index only access can be facilitated by creating an index over BRANCH_INFO that
includes EMP_ID and HOME_BRANCH as key fields. The first to facilitate the probe, the second to prevent
unnecessary access to the BRANCH_INFO table.

CREATE PERMISSION TELLER_ROW_ACCESS ON CUSTOMER


-------------------------------------------------------
-- Teller information:
-- Group TELLER is allowed to access customer data only
-- in their branch.
------------------------------------------------------------
FOR ROWS WHERE VERIFY_GROUP_FOR_USER(SESSION_USER, 'TELLER') = 1
AND
BRANCH = (SELECT HOME_BRANCH FROM BRANCH_INFO WHERE EMP_ID = SESSION_USER)

114 IBM i: Performance and Query Optimization


ENFORCED FOR ALL ACCESS
ENABLE;

ALTER TABLE CUSTOMER ACTIVATE ROW ACCESS CONTROL;

In the example below, not only are you verifying certain user groups for access to particular patient
records but also masking certain data based on whether the patient has participated in a clinical trial.
Extra security is that physicians can see only patient records for whom they are the primary care provider.

CREATE PERMISSION PCP ON patient


-------------------------------------------------------
-- Primary Care Physician Access
-- Group PCP is allowed to access patient data only
-- AND the Primary Care Physician must be assigned to patient
-- Group RESEARCH are allowed to access patient data for those patients
-- that opted in to a clinical trial
------------------------------------------------------------
FOR ROWS WHERE
(VERIFY_GROUP_FOR_USER(SESSION_USER, 'PCP') = 1
AND
PCPID = (SELECT PCPID FROM PHYSICIAN WHERE PCPUSER = SESSION_USER) )
OR
(VERIFY_GROUP_FOR_USER(SESSION_USER, 'RESEARCH') = 1
AND
(SELECT 1 FROM PATIENTCHOICE C
WHERE PATIENT.patientid = C.patientid
AND C.CHOICE = 'clinical trial'
AND C.VALUE = 'opt-in')=1
)
ENFORCED FOR ALL ACCESS
ENABLE;

CREATE MASK PHARMACY_MASK ON PATIENT FOR


--------------------------------------------------------
-- Medical information:
-- Group PCP is allowed to access the full information in column PHARMACY.
-- For the purposes of drug research, Role DRUG_RESEARCH can
-- conditionally see a patient's medical information
-- provided that the patient has opted-in.
-- In all other cases, null values are rendered as column
-- values.
----------------------------------------------------
COLUMN PHARMACY RETURN
CASE WHEN
VERIFY_GROUP_FOR_USER(SESSION_USER,'PCP') = 1 OR
(VERIFY_GROUP_FOR_USER(SESSION_USER,'DRUG_RSRCH')=1
AND
(SELECT 1 FROM PATIENTCHOICE C
WHERE PATIENT.patientid = C.patientid
AND C.CHOICE = 'drug-research'
AND C.VALUE = 'opt-in')= 1
)
THEN PHARMACY
ELSE NULL
END
ENABLE;

ALTER TABLE PATIENT ACTIVATE ROW ACCESS CONTROL ACTIVATE COLUMN ACCESS CONTROL;

The query in the next example, before the introduction of RCAC policies would have accessed only the
PATIENT table. Now it accesses the PATIENT table and the supporting tables that are associated with the
row and column permissions.
The next graphic is the Visual Explain for the next example query. As you can see, the PATIENT table is
accessed along with any other tables mentioned in the ROW and COLUMN access control.
SELECT * FROM PATIENT WHERE PATIENTID = ?

Database performance and query optimization 115


By clicking the index advised icon that is shown in the next graphic:

You get the resulting index advice depicted in the next graphic that shows that it is not only over the
PATIENT table that is explicitly specified in the query, but also over the supporting RCAC tables.

116 IBM i: Performance and Query Optimization


Not considering additional advice per the introduction of RCAC SQL rules can affect query
performance.

Materialized query tables and RCAC


This section focuses on the consequence of RCAC to your SQL query performance when MQTs are used.
Materialized Query Tables (MQTs) are heavily relied upon by data warehousing applications for better
query performance. RCAC and MQTs coexist in harmony. This means:
1. MQTs must continue to provide their added performance benefit to data warehousing applications.
2. MQTs cannot become a means for gaining access to data protected through RCAC rules that are
specified in the dependent base tables, either through direct access to the MQT or by MQT matching
and substitution.
If a materialized query table that depends on the table (directly or indirectly through a view) for which
access control is being activated and that materialized query table does not already have its own access
control activated, row level access control is implicitly activated for the materialized query table. This
restricts direct access to the contents of the materialized query table. A query that explicitly references
the MQT table before such a row permission is defined returns Row Not Found as if there was no data in
the table.
In this example MQT:

CREATE TABLE MQT1


AS (SELECT patientid, patientname,pcpid,pharmacy
FROM patient
WHERE diagnosis is not null)
DATA INITIALLY IMMEDIATE REFRESH DEFERRED
ENABLE QUERY OPTIMIZATION
MAINTAINED BY USER;

To provide access to this materialized query table, an appropriate row permission can be created, or
an ALTER TABLE DEACTIVATE ROW ACCESS CONTROL on the materialized query table can be issued to
remove the row level protection if that is appropriate. If the query optimizer substitutes one or more
tables in a query with this materialized query table via MQT substitution, the row and column access
controls on the replaced (base) tables remain in effect, and the access controls, if any, on the materialized
query table do not apply.

SELECT * FROM MQT1

results in no rows because it does not have its own RCAC policy and therefore it cannot expose rows per
the PATIENT table.

Database performance and query optimization 117


The following query however can be satisfied by the MQT1

SELECT patientid, patientname, pharmacy FROM patient WHERE patientid>4 and diagnosis is not
null;

Row and column level access control does not affect the REFRESH TABLE statement. The table is
refreshed as if row and column level access controls do not exist.

REFRESH TABLE mqt1;

The graphic below shows the Visual Explain that reflects the MQT match and substitution. Note that had
the MQT1 not surfaced a required value of PCPID for the existing RCAC SQL Rules, it would not be able to
satisfy the query request as an MQT match, even though that field is not in the required select list. In this
example Visual Explain, you can see the MQT1 substituted but also inherited the RCAC rules of the base
table PATIENT.

118 IBM i: Performance and Query Optimization


Index advice of the originating query, which is depicted in the graphic below, includes advice over the
main query table, over the MQT and over the RCAC required tables.

Database performance and query optimization 119


As many MQTs, such as the one below, provide ready made aggregation values so aggregating queries in
a data warehousing environment perform quickly, these MQTs are now likely not to match query requests
with aggregated selection via MQT substitution.
The aggregation is based on the REFRESH TABLE with no RCAC applied and yet the matching is based on
the underlying base table and all its RCAC requirements.

CREATE TABLE MQT_AGG


AS (SELECT pcpid, count(*) patientcnt
FROM patient group by pcpid
)
DATA INITIALLY IMMEDIATE REFRESH DEFERRED
ENABLE QUERY OPTIMIZATION
MAINTAINED BY USER;

The following query, although it appears to be a match for the above MQT_AGG, will not substitute the
MQT per RCAC rules.

SELECT pcpid, count(*) FROM PATIENT WHERE pcpid in ( 1, ...) GROUP BY pcpid

All existing MQTs should be analyzed before deploying RCAC policy on base tables to make sure that
performance does not unexpectedly start to suffer because MQTs are no longer available to facilitate
the request.
Because most aggregating queries are not dealing with 'details' and so possibly less sensitive to the
requirements of RCAC, aggregating MQT over base tables with RCAC might be best deployed by direct
substitution in the query and restriction through table privileges and disabling the default RCAC rule,
restricting all rows, as follows.

ALTER TABLE MQT_AGG DEACTIVATE ROW ACCESS CONTROL;

This deactivates the default RCAC applied due to base tables with RCAC and allows direct access to the
MQT in a warehousing environment.

120 IBM i: Performance and Query Optimization


Optimizing query performance using query optimization tools
Query optimization is an iterative process. You can gather performance information about your queries
and control the processing of your queries.

Db2 for IBM i – Health Center


Use the Db2 for IBM i Health Center to capture information about your database. You can view the total
number of objects, the size limits of selected objects, the design limits of selected objects, environmental
limits, and activity level.

Navigator view of Health Center


The System i Navigator provides a robust graphical interface to capture, view, and interact with the Health
Center.
To start the health center, follow these steps:
1. In the System i Navigator window, expand the system that you want to use.
2. Expand Databases.
3. Right-click the database that you want to work with and select Health Center.
You can change your preferences by clicking Change and entering filter information. Click Refresh to
update the information.
To save your health center history, do the following:
1. In the System i Navigator window, expand the system you want to use.
2. Expand Databases.
3. Right-click the database that you want to work with and select Health Center.
4. On the health center dialog, select the area that you want to save. For example, if you want to save the
current overview, click Save on the Overview tab. Size limits and Design limits are not saved.
5. Specify a schema and table to save the information. You can view the contents of the selected table
by clicking View Contents. If you select to save information to a table that does not exist, the system
creates the table for you.

Health Center SQL procedures


The Health Center is implemented upon several Db2 for i SQL procedures.
IBM i users can call the Health Center SQL procedures directly.

QSYS2.Health_Database_Overview ()
The QSYS2.Health_Database_Overview() procedure returns counts of all the different types of Db2 for i
objects within the target schema or schemas. The counts are broken down by object type and subtype.

Procedure definition:
CREATE PROCEDURE QSYS2.HEALTH_DATABASE_OVERVIEW(
IN ARCHIVE_OPTION INTEGER,
IN OBJECT_SCHEMA VARCHAR(258),
IN NUMBER_OF_ITEMS_ARCHIVE INTEGER,
IN OVERVIEW_SCHEMA VARCHAR(258),
IN OVERVIEW_TABLE VARCHAR(258))
DYNAMIC RESULT SETS 1
LANGUAGE C
SPECIFIC QSYS2.HEALTH_DATABASE_OVERVIEW
NOT DETERMINISTIC
MODIFIES SQL DATA
CALLED ON NULL INPUT
EXTERNAL NAME 'QSYS/QSQHEALTH(OVERVIEW)'
PARAMETER STYLE SQL;

Database performance and query optimization 121


Service Program Name: QSYS/QSQHEALTH
Default Public Authority: *USE
Threadsafe: Yes

IBM i release
This procedure was added to IBM i in V5R4M0.

Parameters
Archive_Option (Input) The type of operation to perform for the Db2 for i Health Center
overview detail.
The supported values are:
• 1 = Query only, no archive action is taken
• 2 = Archive only
• 3 = Create archive and archive
• 4 = Query the archive
Note: Option 1 produces a new result set. Options 2 and 3 simply use the
results from the last Query option. Option 3 fails if the archive exists.

Object_Schema (Input) The target schema or schemas for this operation. A single schema
name can be entered. The ‘%' character can be used to direct the
procedure to process all schemas with names that start with the same
characters which appear before the ‘%'. When this parameter contains
only the ‘%' character, the procedure processes all schemas within the
database.
Number_Of_Items_Archive (Input) The number of rows to archive.
The archive can be used to recognize trends over time. To have meaningful
historical comparisons, choose the row count size carefully. This argument
is ignored if the Archive_Option is 1.

Overview_Table (Input) The table that contains the database overview archive.
This argument is ignored if the Archive_Option is 1.

Authorities
To query an existing archive, *USE object authority is required for the Overview_Schema and
Overview_Table. To create an archive, *CHANGE object authority is required for the Overview_Schema.
To add to an existing archive, *CHANGE object authority is required for the Overview_Table and *USE
object authority is required for the Overview_Schema.

Result Set
When Archive_Option is 1 or 4, a single result set is returned.
The format of the result is as follows.
QSYS2.Health_Database_Overview () result set format:

"TIMESTAMP" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,


SCHEMAS BIGINT NOT NULL ,
GRP01 CHAR(1) DEFAULT NULL ,
TABLES BIGINT NOT NULL ,
PARTITIONED_TABLES FOR COLUMN TABLESRT BIGINT NOT NULL ,
DISTRIBUTED_TABLES FOR COLUMN TABLES_DST BIGINT NOT NULL ,
MATERIALIZED_QUERY_TABLES FOR COLUMN TABLES_MAT BIGINT NOT NULL ,

122 IBM i: Performance and Query Optimization


PHYSICAL_FILES FOR COLUMN TABLESHY BIGINT NOT NULL ,
SOURCE_FILES FOR COLUMN TABLES_SRC BIGINT NOT NULL ,
GRP02 CHAR(1) DEFAULT NULL ,
VIEWS BIGINT NOT NULL ,
LOGICAL_FILES FOR COLUMN VIEWS_LGL BIGINT NOT NULL ,
GRP03 CHAR(1) DEFAULT NULL ,
BINARY_RADIX_INDEXES FOR COLUMN INDEXES_BI BIGINT NOT NULL ,
EVI_INDEXES FOR COLUMN INDEXES_EV BIGINT NOT NULL ,
GRP04 CHAR(1) DEFAULT NULL ,
PRIMARY_KEY_CONSTRAINTS FOR COLUMN CSTSRI BIGINT NOT NULL ,
UNIQUE_CONSTRAINTS FOR COLUMN CSTS_UNQ BIGINT NOT NULL ,
CHECK_CONSTRAINTS FOR COLUMN CSTS_CHK BIGINT NOT NULL ,
REFERENTIAL_CONSTRAINTS FOR COLUMN CSTS_RI BIGINT NOT NULL ,
GRP05 CHAR(1) DEFAULT NULL ,
EXTERNAL_TRIGGERS FOR COLUMN TRGS_EXT BIGINT NOT NULL ,
SQL_TRIGGERS FOR COLUMN TRGS_SQL BIGINT NOT NULL ,
INSTEAD_OF_TRIGGERS FOR COLUMN TRGS_INSTD BIGINT NOT NULL ,
GRP06 CHAR(1) DEFAULT NULL ,
ALIASES BIGINT NOT NULL ,
DDM_FILES BIGINT NOT NULL ,
GRP07 CHAR(1) DEFAULT NULL ,
EXTERNALROCEDURES FOR COLUMN PROCS_EXT BIGINT NOT NULL ,
SQLROCEDURES FOR COLUMN PROCS_SQL BIGINT NOT NULL ,
GRP08 CHAR(1) DEFAULT NULL ,
EXTERNAL_SCALAR_FUNCTIONS FOR COLUMN FUNCS_EXTS BIGINT NOT NULL ,
EXTERNAL_TABLE_FUNCTIONS FOR COLUMN FUNCS_EXTT BIGINT NOT NULL ,
SOURCE_SCALAR_FUNCTIONS FOR COLUMN FUNCS_SRCS BIGINT NOT NULL ,
SOURCE_AGGREGATE_FUNCTIONS FOR COLUMN FUNCS_SRCA BIGINT NOT NULL ,
SQL_SCALAR_FUNCTIONS FOR COLUMN FUNCS_SQLS BIGINT NOT NULL ,
SQL_TABLE_FUNCTIONS FOR COLUMN FUNCS_SQLT BIGINT NOT NULL ,
GRP09 CHAR(1) DEFAULT NULL ,
SEQUENCES BIGINT NOT NULL ,
SQLACKAGES FOR COLUMN SQLPKGS BIGINT NOT NULL ,
USER_DEFINED_DISTINCT_TYPES FOR COLUMN UDTS BIGINT NOT NULL ,
JOURNALS BIGINT NOT NULL ,
JOURNAL_RECEIVERS FOR COLUMN JRNRCV BIGINT NOT NULL ,
"SCHEMA" VARCHAR(258) ALLOCATE(10) NOT NULL

LABEL ON COLUMN <result set>


( "TIMESTAMP" IS 'Timestamp' ,
SCHEMAS IS 'Schemas' ,
GRP01 IS 'Tables' ,
TABLES IS 'Non-partitioned tables' ,
PARTITIONED_TABLES IS 'Partitioned tables' ,
DISTRIBUTED_TABLES IS 'Distributed tables' ,
MATERIALIZED_QUERY_TABLES IS 'Materialized query tables' ,
PHYSICAL_FILES IS 'Physical files' ,
SOURCE_FILES IS 'Source files' ,
GRP02 IS 'Views' ,
VIEWS IS 'Views' ,
LOGICAL_FILES IS 'Logical files' ,
GRP03 IS 'Indexes' ,
BINARY_RADIX_INDEXES IS 'Binary radix indexes' ,
EVI_INDEXES IS 'Encoded vector indexes' ,
GRP04 IS 'Constraints' ,
PRIMARY_KEY_CONSTRAINTS IS 'PRIMARY KEY constraints' ,
UNIQUE_CONSTRAINTS IS 'UNIQUE constraints' ,
CHECK_CONSTRAINTS IS 'CHECK constraints' ,
REFERENTIAL_CONSTRAINTS IS 'Referential constraints' ,
GRP05 IS 'Triggers' ,
EXTERNAL_TRIGGERS IS 'External triggers' ,
SQL_TRIGGERS IS 'SQL triggers' ,
INSTEAD_OF_TRIGGERS IS 'INSTEAD OF triggers' ,
GRP06 IS 'Aliases' ,
ALIASES IS 'Aliases' ,
DDM_FILES IS 'DDM files' ,
GRP07 IS 'Procedures' ,
EXTERNALROCEDURES IS 'External procedures' ,
SQLROCEDURES IS 'SQL procedures' ,
GRP08 IS 'Functions' ,
EXTERNAL_SCALAR_FUNCTIONS IS 'External scalar functions' ,
EXTERNAL_TABLE_FUNCTIONS IS 'External table functions' ,
SOURCE_SCALAR_FUNCTIONS IS 'Source scalar functions' ,
SOURCE_AGGREGATE_FUNCTIONS IS 'Source aggregate functions' ,
SQL_SCALAR_FUNCTIONS IS 'SQL scalar functions' ,
SQL_TABLE_FUNCTIONS IS 'SQL table functions' ,
GRP09 IS 'Miscellaneous' ,
SEQUENCES IS 'Sequences' ,
SQLACKAGES IS 'SQL packages' ,
USER_DEFINED_DISTINCT_TYPES IS 'User-defined distinct types' ,
JOURNALS IS 'Journals' ,

Database performance and query optimization 123


JOURNAL_RECEIVERS IS 'Journal receivers' ,
"SCHEMA" IS 'Schema mask' ) ;

Error Messages
Table 34. Error messages
Message ID Error Message Text
SQL0462 W This warning appears in the job log if the procedure encounters objects for
which the user does not have *USE object authority. The warning is provided as
an indication that the procedure was unable to process all available objects.

Usage Notes
None

Related Information
None

Examples
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 1311.

Example 1
Retrieve the overview for the entire database.

CALL QSYS2.Health_Database_Overview(1, '%', NULL, NULL, NULL);

Example results in System i Navigator:

124 IBM i: Performance and Query Optimization


Example 2
Archive all rows in the overview to an SQL table named MYLIB/ARCHIVE1.

CALL QSYS2.Health_Database_Overview(3, '%', 2147483647, 'MYLIB', 'ARCHIVE1')

Example 3
Retrieve the overview from MYLIB/ARCHIVE1.

CALL QSYS2.Health_Database_Overview(4, '%', NULL, 'MYLIB', 'ARCHIVE1')

Example results in System i Navigator:

Database performance and query optimization 125


QSYS2.Health_Activity ()
The QSYS2.Health _Activity () procedure returns summary counts of database and SQL operations over a
set of objects within one or more schemas.

Procedure definition:
CREATE PROCEDURE QSYS2.HEALTH_ACTIVITY(
IN ARCHIVE_OPTION INTEGER,
IN REFRESH_CURRENT_VALUES INTEGER,
IN OBJECT_SCHEMA VARCHAR(258),
IN OBJECT_NAME VARCHAR(258),
IN NUMBER_OBJECTS_ACTIVITY_TO_ARCHIVE INTEGER,
IN NUMBER_OF_ACTIVITY_ARCHIVE INTEGER,
IN ACTIVITY_SCHEMA VARCHAR(258),
IN ACTIVITY_TABLE VARCHAR(258))
DYNAMIC RESULT SETS 1
LANGUAGE C
SPECIFIC QSYS2.HEALTH_ACTIVITY
NOT DETERMINISTIC
MODIFIES SQL DATA
CALLED ON NULL INPUT
EXTERNAL NAME 'QSYS/QSQHEALTH(ACTIVITY)'
PARAMETER STYLE SQL;

Service Program Name: QSYS/QSQHEALTH


Default Public Authority: *USE
Threadsafe: Yes

IBM i release
This procedure was added to IBM i 6.1.

Parameters
Archive_Option (Input) The type of operation to perform for the Db2 for i Health
Center overview detail.

126 IBM i: Performance and Query Optimization


The supported values are:
• 1 = Query only, no archive action is taken
• 2 = Archive only
• 3 = Create archive and archive
• 4 = Query the archive
Note: Option 1 produces a new result set. Options 2 and 3
simply use the results from the last Query option. Option 3 fails
if the archive exists.

Refresh_Current_Values (Input) This option directs how the archive operation is done.
This option is only valid with archive options 2 and 3.
The supported values are:
• 0 = No. Indicates that we capture the activity on the entire set
of specified schemas and objects.
• 1 = Yes. Indicates that we only refresh the activity of the
objects previously captured (based on the short names).
• 2 = None. Use the results from the prior call. A call must have
been performed in this job before using this option

Object_Schema (Input) The target schema or schemas for this operation. A


single schema name can be entered. The ‘%' character can be
used to direct the procedure to process all schemas with names
that start with the same characters which appear before the
‘%'. When this parameter contains only the ‘%' character, the
procedure processes all schemas within the database.
This name also affects the items refreshed if
Refresh_Current_Values = 1.

Object_Name (Input) The target object name for this operation. Only the ‘%'
character is treated as a wildcard since an underscore is a valid
character in a name. The name must be delimited, if necessary,
and case sensitive.
This name also affects the items refreshed if
Refresh_Current_Values = 1.

Number_Objects_Activity_to_Archive (Input) The number of objects to save for each activity.


Number_Of_Activity_Archive (Input) The number of rows to save per object activity.
The archive can be used to recognize trends over time. To have
meaningful historical comparisons, choose the row count size
carefully. This argument is ignored if the Archive_Option is 1 or
4.

Activity_Schema (Input) The table that contains the database activity archive.
This argument is ignored if the Archive_Option is 1.

Activity_Table The table that contains the database activity archive.


This argument is ignored if the Archive_Option is 1.

Database performance and query optimization 127


Authorities
To query an existing archive, *USE object authority is required for the Activity_Schema and Activity_Table.
To create an archive, *CHANGE object authority is required for the Activity_Schema. To add to an existing
archive, *CHANGE object authority is required for the Activity_Table and *USE object authority is required
for the Activity_Schema.
When Archive_Option is 1 or 3, *USE object authority is required for the Object_Schema and for any
objects which are indicated by Object_Name. When an object is encountered and the caller does not have
*USE object authority, an SQL0462 warning is placed in the job log. The object is skipped and not included
in the procedure result set.

Result Set
When Archive_Option is 1 or 4, a single result set is returned.
The format of the result is as follows. All these items were added for IBM i 6.1.
QSYS2.Health_Activity() result set format:

"TIMESTAMP" TIMESTAMP NOT NULL,


ACTIVITY VARCHAR(2000) ALLOCATE(20) DEFAULT NULL,
CURRENT_VALUE FOR COLUMN "VALUE" BIGINT DEFAULT NULL,
OBJECT_SCHEMA FOR COLUMN BSCHEMA VARCHAR(128)ALLOCATE(10) DEFAULT NULL,
OBJECT_NAME FOR COLUMN BNAME VARCHAR(128) ALLOCATE(20) DEFAULT NULL,
OBJECT_TYPE FOR COLUMN BTYPE VARCHAR(24) ALLOCATE(10) DEFAULT NULL,
SYSTEM_OBJECT_SCHEMA FOR COLUMN SYS_DNAME VARCHAR(10) ALLOCATE(10)DEFAULT NULL,
SYSTEM_OBJECT_NAME FOR COLUMN SYS_ONAME VARCHAR(10) ALLOCATE(10) DEFAULT NULL,
PARTITION_NAME FOR COLUMN MBRNAME VARCHAR(10) ALLOCATE(10) DEFAULT NULL,
ACTIVITY_ID FOR COLUMN ACTIV00001 INTEGER DEFAULT NULL

LABEL ON COLUMN <result set>


("TIMESTAMP" IS 'Timestamp',
ACTIVITY IS 'Activity',
CURRENT_VALUE IS 'Current Value',
OBJECT_SCHEMA IS 'Object Schema',
OBJECT_NAME IS 'Object Name',
OBJECT_TYPE IS 'Object Type',
SYSTEM_OBJECT_SCHEMA IS 'System Object Schema',
SYSTEM_OBJECT_NAME IS 'System Object Name',
PARTITION_NAME IS 'Partition Name',
ACTIVITY_ID IS 'Activity ID');

Limit Detail
The supported Database Health Center Activity can be seen on any machine by executing this query. The
supported value column contains zeros because this category of Health Center information is not tied to a
limit.

SELECT * FROM QSYS2.SQL_SIZING WHERE SIZING_ID BETWEEN 18000 AND 18199;

Note: The bold rows were added in IBM i 7.1.

Table 35. Summary counts of database and SQL operations within a schema.
SIZING_ID SIZING_NAME SUPPORTED_VALUE
18100 INSERT OPERATIONS 0
18101 UPDATE OPERATIONS 0
18102 DELETE OPERATIONS 0
18103 LOGICAL READS 0
18104 PHYSICAL READS 0
18105 CLEAR OPERATIONS 0

128 IBM i: Performance and Query Optimization


Table 35. Summary counts of database and SQL operations within a schema. (continued)
SIZING_ID SIZING_NAME SUPPORTED_VALUE
18106 INDEX BUILDS/REBUILDS 0
18107 DATA SPACE REORGANIZE OPERATIONS 0
18108 DATA SPACE COPY OPERATIONS 0
18109 FULL OPENS 0
18110 FULL CLOSES 0
18111 DAYS USED 0
18112 INDEX QUERY USE 0
18113 INDEX QUERY STATISTICS USE 0
18114 INDEX LOGICAL READS 0
18115 INDEX RANDOM READS 0
18116 SQL STATEMENT COMPRESSION COUNT 0
18117 SQL STATEMENT CONTENTION COUNT 0
18118 RANDOM READS 0
18119 SEQUENTIAL READS 0

Error Messages
Table 36. Error messages
Message ID Error Message Text
SQL0462 W This warning appears in the job log if the procedure encounters objects for
which the user does not have *USE object authority. The warning is provided as
an indication that the procedure was unable to process all available objects.

Usage Notes
None

Related Information
None

Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 1311.
Retrieve the activity information for all objects within the QSYS2 schema, using a maximum of 10 objects
per each activity.

CALL QSYS2.Health_Activity(1, 0, 'QSYS2', '%', 10, NULL, NULL, NULL);

Example results in System i Navigator:

Database performance and query optimization 129


130 IBM i: Performance and Query Optimization
QSYS2.Health_Design_Limits ()
The QSYS2.Health_Design_Limits () procedure returns detailed counts of design limits over a set of
objects within one or more schemas. Design limits correspond to architectural constructs, such as
‘Maximum number of columns in a table or view'.

Procedure definition:
CREATE PROCEDURE QSYS2.HEALTH_DESIGN_LIMITS(
ARCHIVE_OPTION INTEGER,
IN REFRESH_CURRENT_VALUES INTEGER,
IN OBJECT_SCHEMA VARCHAR(258),
IN OBJECT_NAME VARCHAR(258),
IN NUMBER_OBJECTS_LIMIT_TO_ARCHIVE INTEGER,
IN NUMBER_OF_LIMITS_ARCHIVE INTEGER,
IN LIMIT_SCHEMA VARCHAR(258),
IN LIMIT_TABLE VARCHAR(258),
DYNAMIC RESULT SETS 1
LANGUAGE C
SPECIFIC QSYS2.HEALTH_DESIGN_LIMITS
NOT DETERMINISTIC
MODIFIES SQL DATA
CALLED ON NULL INPUT
EXTERNAL NAME 'QSYS/QSQHEALTH(DESIGN)'
PARAMETER STYLE SQL;

Service Program Name: QSYS/QSQHEALTH


Default Public Authority: *USE
Threadsafe: Yes

IBM i release
This procedure was added to IBM i V5R4M0.

Parameters
Archive_Option (Input) The type of operation to perform for the Db2 for i Health
Center activity detail.
The supported values are:
• 1 = Query only, no archive action is taken
• 2 = Archive only
• 3 = Create archive and archive
• 4 = Query the archive
Note: Option 1 produces a new result set. Options 2 and 3 simply
use the results from the last Query option. Option 3 fails if the
archive exists.

Refresh_Current_Values (Input) This option directs how the archive operation is done. This
option is only valid with archive options 2 and 3.
The supported values are:
• 0 = No. Indicates that we capture the activity on the entire set of
specified schemas and objects.
• 1 = Yes. Indicates that we only refresh the activity of the objects
previously captured (based on the short names).
• 2 = None. Use the results from the prior call. A call must have
been performed in this job before using this option

Database performance and query optimization 131


Object_Schema (Input) The target schema or schemas for this operation. A single
schema name can be entered. The ‘%' character can be used
to direct the procedure to process all schemas with names that
start with the same characters which appear before the ‘%'. When
this parameter contains only the ‘%' character, the procedure
processes all schemas within the database.
This name also affects the items refreshed if
Refresh_Current_Values = 1.

Object_Name (Input) The target object name for this operation. Only the ‘%'
character is treated as a wildcard since an underscore is a valid
character in a name. The name must be delimited, if necessary,
and case sensitive.
This name also affects the items refreshed if
Refresh_Current_Values = 1.

Number_Objects_Limit_to_Archive (Input) The number of objects to save for each design limit.
Number_Of_Limits_Archive (Input) The number of rows to save per object design limit.
The archive can be used to recognize trends over time. To have
meaningful historical comparisons, choose the row count size
carefully. This argument is ignored if the Archive_Option is 1 or
4.

Limit_Schema (Input) The schema that contains the database limit archive.
This argument is ignored if the Archive_Option is 1.

Limit_Table The table that contains the database limit archive.


This argument is ignored if the Archive_Option is 1.

Authorities
To query an existing archive, *USE object authority is required for the Limit_Schema and Limit_Table.
To create an archive, *CHANGE object authority is required for the Limit_Schema. To add to an archive,
*CHANGE object authority is required for the Limit_Table.
When Archive_Option is 1 or 3, *USE object authority is required for the Object_Schema and for any
objects which are indicated by Object_Name. When an object is encountered and the caller does not have
*USE object authority, an SQL0462 warning is placed in the job log. The object is skipped and not included
in the procedure result set.

Result Set
When Archive_Option is 1 or 4, a single result set is returned.
The format of the result is as follows. All these items were added for IBM i V5R4M0.
QSYS2.Health_Design_Limits() result set format:

"TIMESTAMP" TIMESTAMP NOT NULL,


LIMIT VARCHAR(2000) ALLOCATE(20) DEFAULT NULL,
CURRENT_VALUE FOR COLUMN "VALUE" BIGINT DEFAULT NULL,
PERCENT DECIMAL(5, 2) DEFAULT NULL,
OBJECT_SCHEMA FOR COLUMN BSCHEMA VARCHAR(128) ALLOCATE(10) DEFAULT NULL,
OBJECT_NAME FOR COLUMN BNAME VARCHAR(128) ALLOCATE(20) DEFAULT NULL,
OBJECT_TYPE FOR COLUMN BTYPE VARCHAR(24) ALLOCATE(10) DEFAULT NULL,
SYSTEM_OBJECT_SCHEMA FOR COLUMN SYS_DNAME VARCHAR(10) ALLOCATE(10) DEFAULT NULL,
SYSTEM_OBJECT_NAME FOR COLUMN SYS_ONAME VARCHAR(10) ALLOCATE(10) DEFAULT NULL,
PARTITION_NAME FOR COLUMN MBRNAME VARCHAR(10) ALLOCATE(10) DEFAULT NULL

132 IBM i: Performance and Query Optimization


MAXIMUM_VALUE FOR COLUMN "MAXVALUE" BIGINT DEFAULT NULL
LIMIT_ID INTEGER DEFAULT NULL

LABEL ON COLUMN <result set>


( "TIMESTAMP" IS 'Timestamp',
LIMIT IS 'Limit',
CURRENT_VALUE IS 'Current Value',
PERCENT IS 'Percent',
OBJECT_SCHEMA IS 'Object Schema',
OBJECT_NAME IS 'Object Name',
OBJECT_TYPE IS 'Object Type',
SYSTEM_OBJECT_SCHEMA IS 'System Object Schema',
SYSTEM_OBJECT_NAME IS 'System Object Name',
PARTITION_NAME IS 'Partition Name',
MAXIMUM_VALUE IS 'Maximum Value',
LIMIT_ID IS 'Limit ID');

Limit Detail
The supported Database Health Center Design limits can be seen on any machine by executing this query:

SELECT * FROM QSYS2.SQL_SIZING WHERE SIZING_ID BETWEEN 16000 AND 16999;

Table 37. Design limits over objects within a schema.


SIZING_ID SIZING_NAME SUPPORTED_VALUE
16100 MAXIMUM NUMBER OF MEMBERS 327670
16101 MAXIMUM NUMBER OF RECORD FORMATS 32
16800 MAXIMUM JOURNAL RECEIVER SIZE 1.09951E+12 (~1 TB)
16801 TOTAL SQL STATEMENTS 0
16802 TOTAL ACTIVE SQL STATEMENTS 0
16803 MAXIMUM SQL PACKAGE SIZE 520093696 (~500 MB)
16804 MAXIMUM LARGE SQL PACKAGE SIZE 1056964608 (~1 GB)
16805 MAXIMUM SQL PROGRAM ASSOCIATED SPACE SIZE 16777216

Error Messages
Table 38. Error messages
Message ID Error Message Text
SQL0462 W This warning appears in the job log if the procedure encounters objects for
which the user does not have *USE object authority. The warning is provided as
an indication that the procedure was unable to process all available objects.

Usage Notes
None

Related Information
None

Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 1311.

Database performance and query optimization 133


Retrieve the design limit information for all object names which start with the letter R, within the SYSIBM
schema, using a maximum of 20 objects per each design limit.

CALL QSYS2.Health_Design_Limits(1, 0, 'SYSIBM', 'R%', 20, NULL, NULL, NULL);

Example results in System i Navigator:

QSYS2.Health_Size_Limits ()
The QSYS2.Health_Size_Limits () procedure returns detailed size information for database objects within
one or more schemas. Size limits help you understand trends towards reaching a database limit such as
‘Maximum size of the data in a table partition'.

Procedure definition:
CREATE PROCEDURE QSYS2.HEALTH_SIZE_LIMITS(
IN ARCHIVE_OPTION INTEGER,
IN REFRESH_CURRENT_VALUES INTEGER,
IN OBJECT_SCHEMA VARCHAR(258),
IN OBJECT_NAME VARCHAR(258),
IN NUMBER_OBJECTS_LIMIT_TO_ARCHIVE INTEGER,
IN NUMBER_OF_LIMITS_ARCHIVE INTEGER,
IN LIMIT_SCHEMA VARCHAR(258),
IN LIMIT_TABLE VARCHAR(258))
DYNAMIC RESULT SETS 1
LANGUAGE C
SPECIFIC QSYS2.HEALTH_SIZE_LIMITS

134 IBM i: Performance and Query Optimization


NOT DETERMINISTIC
MODIFIES SQL DATA
CALLED ON NULL INPUT
EXTERNAL NAME 'QSYS/QSQHEALTH(SIZE)'
PARAMETER STYLE SQL;

Service Program Name: QSYS/QSQHEALTH


Default Public Authority: *USE
Threadsafe: Yes

IBM i release
This procedure was added to IBM i V5R4M0.

Parameters
Archive_Option (Input) The type of operation to perform for the Db2 for i Health
Center activity detail.
The supported values are:
• 1 = Query only, no archive action is taken
• 2 = Archive only
• 3 = Create archive and archive
• 4 = Query the archive
Note: Option 1 produces a new result set. Options 2 and 3 simply
use the results from the last Query option. Option 3 fails if the
archive exists.

Refresh_Current_Values (Input) This option directs how the archive operation is done. This
option is only valid with archive options 2 and 3.
The supported values are:
• 0 = No. Indicates that we capture the activity on the entire set of
specified schemas and objects.
• 1 = Yes. Indicates that we only refresh the activity of the objects
previously captured (based on the short names).
• 2 = None. Use the results from the prior call. A call must have
been performed in this job before using this option

Object_Schema (Input) The target schema or schemas for this operation. A single
schema name can be entered. The ‘%' character can be used
to direct the procedure to process all schemas with names that
start with the same characters which appear before the ‘%'. When
this parameter contains only the ‘%' character, the procedure
processes all schemas within the database.
This name also affects the items refreshed if
Refresh_Current_Values = 1.

Object_Name (Input) The target object name for this operation. Only the ‘%'
character is treated as a wildcard since an underscore is a valid
character in a name. The name must be delimited, if necessary,
and case sensitive.
This name also affects the items refreshed if
Refresh_Current_Values = 1.

Database performance and query optimization 135


Number_Objects_Limit_to_Archive (Input) The number of objects to save for each size limit.
Number_Of_Limits_Archive (Input) The number of rows to save per object size limit.
The archive can be used to recognize trends over time. To have
meaningful historical comparisons, choose the row count size
carefully. This argument is ignored if the Archive_Option is 1 or
4.

Limit_Schema (Input) The schema that contains the database activity archive.
This argument is ignored if the Archive_Option is 1.

Limit_Table The table that contains the database activity archive.


This argument is ignored if the Archive_Option is 1.

Authorities
To query an existing archive, *USE object authority is required for the Limit_Schema and Limit_Table.
To create an archive, *CHANGE object authority is required for the Limit_Schema. To add to an archive,
*CHANGE object authority is required for the Limit_Table.
When Archive_Option is 1 or 3, *USE object authority is required for the Object_Schema and for any
objects which are indicated by Object_Name. When an object is encountered and the caller does not have
*USE object authority, an SQL0462 warning is placed in the job log. The object is skipped and not included
in the procedure result set.

Result Set
When Archive_Option is 1 or 4, a single result set is returned.
The format of the result is as follows.
QSYS2.Health_Size_Limits() result set format:

"TIMESTAMP" TIMESTAMP NOT NULL,


LIMIT VARCHAR(2000) ALLOCATE(20) DEFAULT NULL,
CURRENT_VALUE FOR COLUMN "VALUE" BIGINT DEFAULT NULL,
PERCENT DECIMAL(5, 2) DEFAULT NULL, OBJECT_SCHEMA FOR COLUMN BSCHEMA VARCHAR(128) ALLOCATE(10) DEFAULT
NULL,
OBJECT_NAME FOR COLUMN BNAME VARCHAR(128) ALLOCATE(20) DEFAULT NULL,
OBJECT_TYPE FOR COLUMN BTYPE VARCHAR(24) ALLOCATE(10) DEFAULT NULL,
SYSTEM_OBJECT_SCHEMA FOR COLUMN SYS_DNAME VARCHAR(10) ALLOCATE(10) DEFAULT NULL,
SYSTEM_OBJECT_NAME FOR COLUMN SYS_ONAME VARCHAR(10) ALLOCATE(10) DEFAULT NULL,
MAXIMUM_VALUE FOR COLUMN "MAXVALUE" BIGINT DEFAULT NULL,
LIMIT_ID INTEGER DEFAULT NULL,
PARTITION_NAME FOR COLUMN MBRNAME VARCHAR(10) ALLOCATE(10) DEFAULT NULL,
"SCHEMA" VARCHAR(258) ALLOCATE(10) DEFAULT NULL,
OBJECT VARCHAR(258) ALLOCATE(10) DEFAULT NULL,
"REFRESH" INTEGER DEFAULT NULL

LABEL ON COLUMN <result set>


( "TIMESTAMP" IS 'Timestamp',
LIMIT IS 'Limit',
CURRENT_VALUE IS 'Current Value',
PERCENT IS 'Percent',
OBJECT_SCHEMA IS 'Object Schema',
OBJECT_NAME IS 'Object Name',
OBJECT_TYPE IS 'Object Type',
SYSTEM_OBJECT_SCHEMA IS 'System Object Schema',
SYSTEM_OBJECT_NAME IS 'System Object Name',
MAXIMUM_VALUE IS 'Maximum Value',
LIMIT_ID IS 'Limit ID',
PARTITION_NAME IS 'Partition Name',
"SCHEMA" IS 'Schema Mask',
OBJECT IS 'Object Mask',
"REFRESH" IS 'Refresh');

136 IBM i: Performance and Query Optimization


Limit Detail
The supported Database Health Center Size limits can be seen on any machine by executing this query:

SELECT * FROM QSYS2.SQL_SIZING WHERE SIZING_ID BETWEEN 15000 AND 15999;

Table 39. Size limit information for database objects within a schema.
SIZING_ID SIZING_NAME SUPPORTED_VALUE
15000 MAXIMUM NUMBER OF ALL ROWS 4.29E+09
15001 MAXIMUM NUMBER OF VALID ROWS 4.29E+09
15002 MAXIMUM NUMBER OF DELETED ROWS 4.29E+09
15003 MAXIMUM TABLE PARTITION SIZE 1.7E+12
15004 MAXIMUM NUMBER OF OVERFLOW ROWS 4.29E+09
15101 MAXIMUM ROW LENGTH 32766
15102 MAXIMUM ROW LENGTH WITH LOBS 3.76E+09
15103 MAXIMUM NUMBER OF PARTITIONS 256
15150 MAXIMUM NUMBER OF REFERENCED TABLES 256
15300 MAXIMUM NUMBER OF TRIGGERS 300
15301 MAXIMUM NUMBER OF CONSTRAINTS 300
15302 MAXIMUM LENGTH OF CHECK CONSTRAINT 2097151
15400 MAXIMUM *MAX4GB INDEX SIZE 4.29E+09
15401 MAXIMUM *MAX1TB INDEX SIZE 1.7E+12
15402 MAXIMUM NUMBER OF INDEX ENTRIES 0
15500 MAXIMUM KEY COLUMNS 120
15501 MAXIMUM KEY LENGTH 32767
15502 MAXIMUM NUMBER OF PARTITIONING KEYS 120
15700 MAXIMUM NUMBER OF FUNCTION PARAMETERS 2000
15701 MAXIMUM NUMBER OF PROCEDURE PARAMETERS 2000

Error Messages
Table 40. Error messages
Message ID Error Message Text
SQL0462 W This warning appears in the job log if the procedure encounters objects for
which the user does not have *USE object authority. The warning is provided as
an indication that the procedure was unable to process all available objects.

Usage Notes
None

Related Information
None

Database performance and query optimization 137


Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 1311.
Retrieve the size limit information for all object names which start with the letter S, within the SYSIBM
schema, using a maximum of five objects per each design limit.

CALL QSYS2.Health_Size_Limits(1, 0, 'SYSIBM', 'S%', 5, NULL, NULL, NULL);

Example results in System i Navigator:

QSYS2.Health_Environmental_Limits ()
The QSYS2.Health_Environmental_Limits() procedure returns detail on the top 10 jobs on the system,
for different SQL or application limits. The jobs do not have to be in existence. The top 10 information is
maintained within Db2 for i and gets reset when the machine is IPLed, the IASP is varied ON, or when the
QSYS2.Reset_Environmental_Limits() procedure is called.

Procedure definition:
CREATE PROCEDURE QSYS2.HEALTH_ENVIRONMENTAL_LIMITS(
IN ARCHIVE_OPTION INTEGER,
IN NUMBER_OF_LIMITS_ARCHIVE INTEGER,
IN LIMIT_SCHEMA VARCHAR(258),
IN LIMIT_TABLE VARCHAR(258))
DYNAMIC RESULT SETS 1
LANGUAGE C
SPECIFIC QSYS2.HEALTH_ENVIRONMENTAL_LIMITS

138 IBM i: Performance and Query Optimization


NOT DETERMINISTIC
MODIFIES SQL DATA
CALLED ON NULL INPUT
EXTERNAL NAME 'QSYS/QSQHEALTH(ENVIRON)'
PARAMETER STYLE SQL;

Service Program Name: QSYS/QSQHEALTH


Default Public Authority: *USE
Threadsafe: Yes

IBM i release
This procedure was added to IBM i 6.1.

Parameters
Archive_Option (Input) The type of operation to perform for the Db2 for i Health Center
activity detail.
The supported values are:
• 1 = Query only, no archive action is taken
• 2 = Archive only
• 3 = Create archive and archive
• 4 = Query the archive
Note: Option 1 produces a new result set. Options 2 and 3 simply use the
results from the last Query option. Option 3 fails if the archive exists.

Number_Of_Limits_Archive (Input) The number of rows to save per object health limit.
The archive can be used to recognize trends over time. To have meaningful
historical comparisons, choose the row count size carefully. This argument
is ignored if the Archive_Option is 1 or 4.

Limit_Schema (Input) The schema that contains the database activity archive.
This argument is ignored if the Archive_Option is 1.

Limit_Table The table that contains the database activity archive.


This argument is ignored if the Archive_Option is 1.

Authorities
To query an existing archive, *USE object authority is required for the Limit_Schema and Limit_Table.
To create an archive, *CHANGE object authority is required for the Limit_Schema. To add to an archive,
*CHANGE object authority is required for the Limit_Table.
When Archive_Option is 1 or 3, *USE object authority is required for the Object_Schema and for any
objects which are indicated by Object_Name. When an object is encountered and the caller does not have
*USE object authority, an SQL0462 warning is placed in the job log. The object is skipped and not included
in the procedure result set.

Result Set
When Archive_Option is 1 or 4, a single result set is returned.
The format of the result is as follows. All these items were added for IBM i 6.1.

Database performance and query optimization 139


QSYS2.Health_Environmental_Limits() result set format:

"TIMESTAMP" TIMESTAMP NOT NULL,


LIMIT VARCHAR(2000) ALLOCATE(20) DEFAULT NULL,
HIGHWATER_MARK_VALUE FOR COLUMN HIMARK BIGINT DEFAULT NULL,
WHEN_VALUE_WAS_RECORDED FOR COLUMN TIMEHIT TIMESTAMP NOT NULL,
PERCENT DECIMAL(5, 2) DEFAULT NULL,
JOB_NAME VARCHAR(28) ALLOCATE(20) DEFAULT NULL,
"CURRENT_USER" FOR COLUMN CUSER VARCHAR(128) ALLOCATE(10) DEFAULT NULL,
JOB_TYPE VARCHAR(26) ALLOCATE(20) DEFAULT NULL,
MAXIMUM_VALUE FOR COLUMN MAXVAL BIGINT DEFAULT NULL,
JOB_STATUS VARCHAR(13) DEFAULT NULL,
CLIENT_WRKSTNNAME FOR COLUMN "WRKSTNNAME" VARCHAR(255) DEFAULT NULL,
CLIENT_APPLNAME FOR COLUMN "APPLNAME" VARCHAR(255) DEFAULT NULL,
CLIENT_ACCTNG FOR COLUMN "ACCTNG" VARCHAR(255) DEFAULT NULL,
CLIENTROGRAMID FOR COLUMN "PROGRAMID" VARCHAR(255) DEFAULT NULL,
CLIENT_USERID FOR COLUMN "USERID" VARCHAR(255) DEFAULT NULL,
WHEN_LIMITS_ESTABLISHED FOR COLUMN TIMESET TIMESTAMP NOT NULL,
INTERFACE_NAME FOR COLUMN INTNAME VARCHAR(127) ALLOCATE(10) DEFAULT NULL,
INTERFACE_TYPE FOR COLUMN INTTYPE VARCHAR(63) ALLOCATE(10) DEFAULT NULL,
INTERFACE_LEVEL FOR COLUMN INTLEVEL VARCHAR(63) ALLOCATE(10) DEFAULT NULL,
LIMIT_ID INTEGER DEFAULT NULL

LABEL ON COLUMN <result set>


( "TIMESTAMP" IS 'Timestamp',
LIMIT IS 'Limit',
HIGHWATER_MARK_VALUE IS 'Largest Value',
WHEN_VALUE_WAS_RECORDED IS 'Timestamp When Recorded',
PERCENT IS 'Percent',
JOB_NAME IS 'Job Name',
"CURRENT_USER" IS 'Current User',
JOB_TYPE IS 'Job Type',
MAXIMUM_VALUE IS 'Maximum Value',
JOB_STATUS IS 'Job Status',
CLIENT_WRKSTNNAME IS 'Client Workstation Name',
CLIENT_APPLNAME IS 'Client Application Name',
CLIENT_ACCTNG IS 'Client Accounting Code',
CLIENTROGRAMID IS 'Client Program Identifier',
CLIENT_USERID IS 'Client User Identifier',
WHEN_LIMITS_ESTABLISHED IS 'Timestamp Limits Established',
INTERFACE_NAME IS 'Interface Name' ,
INTERFACE_TYPE IS 'Interface Type',
INTERFACE_LEVEL IS 'Interface Level',
LIMIT_ID IS 'Limit ID' );

Limit Detail
The supported Database Health Center Environmental limits can be seen on any machine by executing
this query:

SELECT * FROM QSYS2.SQL_SIZING WHERE SIZING_ID BETWEEN 18200 AND 18299;

Note: The bold row was added in IBM i 7.1.

Table 41. SQL environmental limits.


SIZING_ID SIZING_NAME SUPPORTED_VALUE
18200 MAXIMUM NUMBER OF LOB or XML LOCATORS PER JOB 16000000
18201 MAXIMUM NUMBER OF LOB or XML LOCATORS PER 209000
SERVER JOB
18202 MAXIMUM NUMBER OF ACTIVATION GROUPS 0
18203 MAXIMUM NUMBER OF DESCRIPTORS 0
18204 MAXIMUM NUMBER OF CLI HANDLES 160000
18205 MAXIMUM NUMBER OF SQL OPEN CURSORS 21754
18206 MAXIMUM NUMBER OF SQL PSEUDO OPEN CURSORS 0

140 IBM i: Performance and Query Optimization


Table 41. SQL environmental limits. (continued)
SIZING_ID SIZING_NAME SUPPORTED_VALUE
18207 MAXIMUM LENGTH OF SQL STATEMENT2097152 2097152

Error Messages
None

Usage Notes
None

Related Information
None

Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 1311.
Retrieve the SQL environmental limits for the current database.

CALL QSYS2.Health_Environmental_Limits(1, 0, NULL, NULL);

Example results in System i Navigator:

Database performance and query optimization 141


QSYS2.Reset_Environmental_Limits ()
The QSYS2.Reset_Environmental_Limits () procedure clears out the environment limit cache for the
database. If IASPs are being used, this procedure clears the environment limit cache for the IASP within
which it is called.

Procedure definition:
CREATE PROCEDURE QSYS2.RESET_ENVIRONMENTAL_LIMITS(
LANGUAGE C
SPECIFIC QSYS2.RESET_ENVIRONMENTAL_LIMITS
NOT DETERMINISTIC
MODIFIES SQL DATA
CALLED ON NULL INPUT
EXTERNAL NAME 'QSYS/QSQSSUDF(RESETENV)'
PARAMETER STYLE SQL;

Service Program Name: QSYS/QSQHEALTH


Default Public Authority: *USE
Threadsafe: Yes

IBM i release
This procedure was added to IBM i 6.1.

Parameters
None.

Authorities
This procedure requires the user to have *JOBCTL user special authority or be authorized to the
QIBM_DB_SQLADM Function through Application Administration in System i Navigator. The Change
Function Usage (CHGFCNUSG) command can also be used to allow or deny use of the function.
For example:

CHGFCNUSG FCNID(QIBM_DB_SQLADM) USER(xxxxx) USAGE(*ALLOWED)

Result Set
None.

Error Messages
Table 42. Error messages
Message ID Error Message Text
SQL0552 Not authorized to PROCEDURE.

Usage Notes
None

Related Information
None

142 IBM i: Performance and Query Optimization


Example
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 1311.
Reset the SQL environmental limits for the current database.

CALL QSYS2.RESET_ENVIRONMENTAL_LIMITS;

Monitoring your queries using the Database Monitor


Start Database Monitor (STRDBMON) command gathers information about a query in real time and
stores this information in an output table. This information can help you determine whether your system
and your queries are performing well, or whether they need fine-tuning. Database monitors can generate
significant CPU and disk storage overhead when in use.
You can gather performance information for a specific query, for every query on the system, or for a group
of queries on the system. When a job is monitored by multiple monitors, each monitor is logging rows to
a different output table. You can identify rows in the output database table by its unique identification
number.
When you start a monitor using the Start Database Monitor (STRDBMON) command, the monitor is
automatically registered with System i Navigator and appears in the System i Navigator monitor list.
Note: Database monitors also contain the SQL statement text and variable values. If the variable values or
SQL statements contain sensitive data you should create database monitors in a library that is not publicly
authorized to prevent exposure to the sensitive data.

What kinds of statistics you can gather


The database monitor provides the same information that is provided with the query optimizer debug
messages (Start Debug (STRDBG)) and the Print SQL information (PRTSQLINF) command.
The following is a sampling of the additional information that is gathered by the database monitors:
• System and job name
• SQL statement and subselect number
• Start and end timestamp
• Estimated processing time
• Total rows in table queried
• Number of rows selected
• Estimated number of rows selected
• Estimated number of joined rows
• Key columns for advised index
• Total optimization time
• Join type and method
• ODP implementation

How you can use performance statistics


You can use these performance statistics to generate various reports. For instance, you can include
reports that show queries that:
• Use an abundance of the system resources.
• Take a long time to execute.
• Did not run because of the query governor time limit.
• Create a temporary index during execution

Database performance and query optimization 143


• Use the query sort during execution
• Might perform faster with the creation of a keyed logical file containing keys suggested by the query
optimizer.
Note: A query that is canceled by an end request generally does not generate a full set of performance
statistics. However, it does contain all the information about how a query was optimized, except for
runtime or multi-step query information.
Related information
Start Debug (STRDBG) command
Print SQL Information (PRTSQLINF) command
Start Database Monitor (STRDBMON) command

Start Database Monitor (STRDBMON) command


The Start Database Monitor (STRDBMON) command starts the collection of database performance
statistics for a specified job, for all jobs on the system or for a selected set of jobs. The statistics are
placed in a user-specified database table and member. If the table or member do not exist, one is created
based on the QAQQDBMN table in library QSYS, with the public authority for the file the same as the
create authority specified for the library in which the file is created. If the table and member do exist, the
record format of the specified table is verified to ensure it is the same.
For each monitor started using the STRDBMON command, the system generates a monitor ID that can
be used to uniquely identify each individual monitor. The monitor ID can be used on the ENDDBMON
command to uniquely identify which monitor is to be ended. The monitor ID is returned in the
informational message CPI436A which is generated for each occurrence of the STRDBMON command.
The monitor ID can also be found in either the column QQC101 of the QQQ3018 database monitor record
or in the QSYS2.DATABASE_MONITOR_INFO catalog.
Informally there are two types of monitors. A private monitor is a monitor over one, specific job (or the
current job). Only one (1) monitor can be started on a specific job at a time. For example, STRDBMON
JOB(*) followed by another STRDBMON JOB(*) within the same job is not allowed. A public monitor
is a monitor which collects data across multiple jobs. There can be a maximum of 10 public monitors
active at any one time. For example, STRDBMON JOB(*ALL) followed by another STRDBMON JOB(*ALL) is
allowed providing the maximum number of public monitors does not exceed 10. You could have 10 public
monitors and 1 private monitor active at the same time for any specific job.
If multiple monitors specify the same output file, only one copy of the database statistic records is
written to the file for each job. For example, STRDBMON OUTFILE(LIB/TABLE1) JOB(*) and STRDBMON
OUTFILE(LIB/TABLE1) JOB(*ALL) target the same output file. For the current job, there are not two copies
of the database statistic records–one copy for the private monitor and one copy for the public monitor.
There is only one copy of the database statistic records.
If the monitor is started on all jobs (a public monitor), any jobs waiting on queues or started during the
monitoring period are included in the monitor data. If the monitor is started on a specific job (a private
monitor) that job must be active in the system when the command is issued. Each job in the system can
be monitored concurrently by one private monitor and a maximum of 10 public monitors.
The STRDBMON command allows you to collect statistic records for a specific set or subset of the queries
running on any job. This filtering can be performed over the job name, user profile, query table names,
query estimated run time, TCP/IP address, or any combination of these filters. Specifying a STRDBMON
filter helps minimize the number of statistic records captured for any monitor.

Example 1: Starting Public Monitoring

STRDBMON OUTFILE(QGPL/FILE1) OUTMBR(MEMBER1 *ADD)


JOB(*ALL) FRCRCD(10))

This command starts database monitoring for all jobs on the system. The performance statistics are
added to the member named MEMBER1 in the file named FILE1 in the QGPL library. 10 records are held
before being written to the file.

144 IBM i: Performance and Query Optimization


Example 2: Starting Private Monitoring

STRDBMON OUTFILE(*LIBL/FILE3) OUTMBR(MEMBER2)


JOB(134543/QPGMR/DSP01) FRCRCD(20)

This command starts database monitoring for job number 134543. The job name is DSP01 and was
started by the user named QPGMR. The performance statistics are added to the member named
MEMBER2 in the file named FILE3. 20 records are held before being written to the file.

Example 3: Starting Private Monitoring to a File in a Library in an Independent ASP

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(134543/QPGMR/DSP01)

This command starts database monitoring for job number 134543. The job name is DSP01 and
was started by the user named QPGMR. The performance statistics are added to the member name
DBMONFILE (since OUTMBR was not specified) in the file named DBMONFILE in the library named LIB41.
This library could exist in more than one independent auxiliary storage pool (ASP); the library in the name
space of the originator's job is always used.

Example 4: Starting Public Monitoring For All Jobs That Begin With 'QZDA

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*ALL/*ALL/QZDA*)

This command starts database monitoring for all jobs that whose job name begins with 'QZDA'. The
performance statistics (monitor records) are added to member DBMONFILE (since OUTMBR was not
specified) in file DBMONFILE in library LIB41. This library could exist in more than one independent
auxiliary storage pool (ASP); the library in the name space of the originator's job is always used.

Example 5: Starting Public Monitoring and Filtering SQL Statements That Run Over 10 Seconds

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*ALL) RUNTHLD(10)

This command starts database monitoring for all jobs. Monitor records are created only for those SQL
statements whose estimated run time meets or exceeds 10 seconds.

Example 6: Starting Public Monitoring and Filtering SQL Statements That Have an Estimated
Temporary Storage Over 200 MB

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*ALL) STGTHLD(200)

This command starts database monitoring for all jobs. Monitor records are created only for those SQL
statements whose estimated temporary storage meets or exceeds 200 MB.

Example 7: Starting Private Monitoring and Filtering Over a Specific File

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*)


FTRFILE(LIB41/TABLE1)

This command starts database monitoring for the current job. Monitor records are created only for those
SQL statements that use file LIB41/TABLE1.

Example 8: Starting Private Monitoring for the Current User

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*) FTRUSER(*CURRENT)

This command starts database monitoring for the current job. Monitor records are created only for those
SQL statements that are executed by the current user.

Database performance and query optimization 145


Example 9: Starting Public Monitoring For Jobs Beginning With 'QZDA' and Filtering Over Run Time
and File

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*ALL/*ALL/QZDA*)


RUNTHLD(10) FTRUSER(DEVLPR1) FTRFILE(LIB41/TTT*)

This command starts database monitoring for all jobs whose job name begins with 'QZDA'. Monitor
records are created only for those SQL statements that meet all the following conditions:
• The estimated run time, as calculated by the query optimizer, meets, or exceeds 10 seconds
• Was executed by user 'DEVLPR1'.
• Use any file whose name begins with 'TTT' and resides in library LIB41.

Example 10: Starting Public Monitoring and Filtering SQL Statements That Have Internet Address
'9.10.111.77'.

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*ALL)


FTRINTNETA('9.10.111.77')

This command starts database monitoring for all jobs. Monitor records are created only for TCP/IP
database server jobs that are using the client IP version 4 address of '9.10.111.77'.

Example 11: Starting Public Monitoring and Filtering SQL Statements That Have a Port Number of
8471

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*ALL) FTRLCLPORT(8471)

This command starts database monitoring for all jobs. Monitor records are created only for TCP/IP
database server jobs that are using the local port number 8471.

Example 12: Starting Public Monitoring Based on Feedback from the Query Governor

CHGSYSVAL QQRYTIMLMT(200)
STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*ALL) FTRQRYGOVR(*COND)

This commands starts database monitoring for all jobs whose estimated run time is expected to exceed
200 seconds, based on the response to the query governor. In this example, data is collected only if the
query is canceled or a return code of 2 is returned by a query governor exit program. The query can be
canceled by a user response to the inquiry message CPA4259, issued because the query exceeded the
query governor limits. It can also be canceled by the program logic inside the registered query governor
exit program.

Example 13: Collecting database monitor for Interactive SQL use

STRDBMON OUTFILE(QGPL/STRSQLMON1) OUTMBR(*FIRST *REPLACE)


JOB(*ALL/*ALL/*ALL) TYPE(*DETAIL)
FTRCLTPGM(STRSQL)

This command uses the database monitor pre-filter by Client Special Register Program ID to collect
monitor records for all the SQL statements executed by Interactive SQL (STRSQL command) usage.

Example 14: Starting Public Monitoring and Filtering SQL Statements Run From IBM i Access Client
Solutions Run SQL Scripts

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*ALL)


FTRCLTAPP('IBM i Access Client Solutions - RUN SQL Scripts')

This command starts database monitoring for all jobs. Monitor records are created only for those
statements where the client special register CLIENT APPLNAME is IBM i Access Client Solutions - RUN
SQL Scripts.

146 IBM i: Performance and Query Optimization


Example 15: Starting Public Monitoring and Filtering SQL Statements Run From IBM System i Access
for Windows Run SQL Scripts

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*ALL)


FTRCLTPGM('cwbunnav.exe')

This command starts database monitoring for all jobs. Monitor records are created only for those
statements where the client special register CLIENT_PROGRAMID is cwbunnav.exe.

Example 16: Starting Public Monitoring and Filtering for the client user dbmusr1

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*ALL)


FTRCLTUSR(dbmusr1)

This command starts database monitoring for all jobs. Monitor records are created only for those
statements where the client special register CLIENT_USERID is dbmusr1.

Example 17: Starting Public Monitoring and Filtering SQL Statements Using FTRUSER

STRDBMON OUTFILE(LIB41/DBMONFILE) JOB(*ALL)


FTRUSER((STC* *NE) (S*) (TS*) (TSA* *NE))

This command starts database monitoring for all jobs. Monitor records are created only for those
statements where the user profile is logically equivalent to: User profile NOT LIKE 'STC%' AND user
profile NOT LIKE 'TSA%' AND (user profile LIKE 'S%' OR user profile LIKE 'TS%')
Related information
Start Database Monitor (STRDBMON) command

End Database Monitor (ENDDBMON) command


The End Database Monitor (ENDDBMON) command ends the collection of database performance
statistics for a specified job, all jobs on the system, or a selected set of jobs (for example, a generic job
name).
To end a monitor, you can specify the job or the monitor ID or both. If only the JOB parameter is specified,
the monitor that was started using the same exact JOB parameter is ended - if there is only one monitor
which matches the specified JOB. If more than one monitor is active which matches the specified JOB,
then the user uniquely identifies which monitor is to be ended by use of the MONID parameter.
When only the MONID parameter is specified, the specified MONID is compared to the monitor ID of the
monitor for the current job and to the monitor ID of all active public monitors (monitors that are open
across multiple jobs). The monitor matching the specified MONID is ended.
The monitor ID is returned in the informational message CPI436A. This message is generated for each
occurrence of the STRDBMON command. Look in the job log for message CPI436A to find the system
generated monitor ID, if needed. The monitor ID can also be found in column QQC101 of the QQQ3018
database monitor record.

Restrictions
• If a specific job name and number or JOB(*) was specified on the Start Database Monitor
(STRDBMON) command, the monitor can only be ended by specifying the same job name and number or
JOB(*) on the ENDDBMON command.
• If JOB(*ALL) was specified on the Start Database Monitor (STRDBMON) command, the monitor
can only be ended by specifying ENDDBMON JOB(*ALL). The monitor cannot be ended by specifying
ENDDBMON JOB(*).
When monitoring is ended for all jobs, all the jobs on the system are triggered to close the database
monitor output table. However, the ENDDBMON command can complete before all the monitored jobs
have written their final statistic records to the log. Use the Work with Object Locks (WRKOBJLCK)

Database performance and query optimization 147


command to determine that all the monitored jobs no longer hold locks on the database monitor output
table before assuming that the monitoring is complete.

Example 1: End Monitoring for a Specific Job

ENDDBMON JOB(*)

This command ends database monitoring for the current job.

Example 2: End Monitoring for All Jobs

ENDDBMON JOB(*ALL)

This command ends the monitor open across all jobs on the system. If more than one monitor with
JOB(*ALL) is active, then the MONID parameter must also be specified to uniquely identify which specific
public monitor to end.

Example 3: End Monitoring for an Individual Public Monitor with MONID Parameter

ENDDBMON JOB(*ALL) MONID(061601001)

This command ends the monitor that was started with JOB(*ALL) and that has a monitor ID of
061601001. Because there were multiple monitors started with JOB(*ALL), the monitor ID must be
specified to uniquely identify which monitor that was started with JOB(*ALL) is to be ended.

Example 4: End Monitoring for an Individual Public Monitor with MONID Parameter

ENDDBMON MONID(061601001)

This command performs the same function as the previous example. It ends the monitor that was started
with JOB(*ALL) or JOB(*) and that has a monitor ID of 061601001.

Example 5: End Monitoring for All JOB(*ALL) Monitors

ENDDBMON JOB(*ALL/*ALL/*ALL) MONID(*ALL)

This command ends all monitors that are active across multiple jobs. It does not end any monitors open
for a specific job or the current job.

Example 6: End Monitoring for a Generic Job

ENDDBMON JOB(QZDA*)

This command ends the monitor that was started with JOB(QZDA*). If more than one monitor with
JOB(QZDA*) is active, then the MONID parameter must also be specified to uniquely identify which
individual monitor to end.

Example 7: End Monitoring for an Individual Monitor with a Generic Job

ENDDBMON JOB(QZDA*) MONID(061601001)

This command ends the monitor that was started with JOB(QZDA*) and has a monitor ID of 061601001.
Because there were multiple monitors started with JOB(QZDA*), the monitor ID must be specified to
uniquely identify which JOB(QZDA*) monitor is to be ended.

Example 8: End Monitoring for a Group of Generic Jobs

ENDDBMON JOB(QZDA*) MONID(*ALL)

148 IBM i: Performance and Query Optimization


This command ends all monitors that were started with JOB(QZDA*).
Related information
End Database Monitor (ENDDBMON) command

Database monitor performance rows


The rows in the database table are uniquely identified by their row identification number. The information
within the file-based monitor (Start Database Monitor (STRDBMON)) is written out based upon a
set of logical formats which are defined in the database monitor formats. These views correlate closely to
the debug messages and the Print SQL Information (PRSQLINF) messages.
The database monitor formats section also identifies which physical columns are used for each view and
what information it contains. You can use the views to identify the information that can be extracted from
the monitor. These rows are defined in several different views which are not shipped with the system
and must be created by the user, if wanted. The views can be created with the SQL DDL. The column
descriptions are explained in the tables following each figure.
Related concepts
Database monitor formats
This section contains the formats used to create the database monitor SQL tables and views.

Database monitor examples


The System i Navigator interface provides a powerful tool for gathering and analyzing performance
monitor data using database monitor. However, you might want to do your own analysis of the database
monitor files.
Suppose you have an application program with SQL statements and you want to analyze and
performance tune these queries. The first step in analyzing the performance is collection of data. The
following examples show how you might collect and analyze data using Start Database Monitor
(STRDBMON) and End Database Monitor (ENDDBMON) commands. Performance data is collected
in LIB/PERFDATA for an application running in your current job. The following sequence collects
performance data and prepares to analyze it.
1. STRDBMON FILE(LIB/PERFDATA) TYPE(*DETAIL). If this table does not exist, the command creates one
from the skeleton table in QSYS/QAQQDBMN.
2. Run your application
3. ENDDBMON
4. Create views over LIB/PERFDATA using the SQL DDL. Creating the views is not mandatory. All the
information resides in the base table that was specified on the STRDBMON command. The views simply
provide an easier way to view the data.
You are now ready to analyze the data. The following examples give you a few ideas on how to use
this data. You must closely study the physical and logical view formats to understand all the data being
collected. Then you can create queries that give the best information for your applications.
Related information
Start Database Monitor (STRDBMON) command
End Database Monitor (ENDDBMON) command

Application with table scans example


Determine which queries in your SQL application are implemented with table scans. The complete
information can be obtained by joining two views: QQQ1000, which contains information about the SQL
statements, and QQQ3000, which contains data about queries performing table scans.
The following SQL query can be used:

SELECT (B.End_Timestamp - B.Start_Timestamp) AS TOT_TIME, A.System_Table_Schema,


A.System_Table_Name,
A.Index_Advised, A.Table_Total_Rows, C.Number_Rows_Returned, A.Estimated_Rows_Selected,
B.Statement_Text_Long

Database performance and query optimization 149


FROM LIB.QQQ3000 A, LIB.QQQ1000 B, LIB.QQQ3019 C
WHERE A.Join_Column = B.Join_Column
AND A.Join_Column = C.Join_Column

Sample output of this query is shown in the following table. Key to this example are the join criteria:

WHERE A.Join_Column = B.Join_Column


AND A.Join_Column = C.Join_Column

Much data about many queries is contained in multiple rows in table LIB/PERFDATA. It is not uncommon
for data about a single query to be contained in 10 or more rows within the table. The combination of
defining the logical views and then joining the views together allows you to piece together all the data for
a query or set of queries. Column QQJFLD uniquely identifies all queries within a job; column QQUCNT is
unique at the query level. The combination of the two, when referenced in the context of the logical views,
connects the query implementation to the query statement information.

Table 43. Output for SQL Queries that Performed Table Scans
Lib Table Total Index Rows TOT_
Name Name Rows Advised Returned TIME Statement Text
LIB1 TBL1 20000 Y 10 6.2
SELECT * FROM LIB1/TBL1
WHERE FLD1 = 'A'

LIB1 TBL2 100 N 100 0.9


SELECT * FROM LIB1/TBL2

LIB1 TBL1 20000 Y 32 7.1


SELECT * FROM LIB1/TBL1
WHERE FLD1 = 'B' AND
FLD2 > 9000

If the query does not use SQL, the SQL information row (QQQ1000) is not created. Without the SQL
information row, it is more difficult to determine which rows in LIB/PERFDATA pertain to which query.
When using SQL, row QQQ1000 contains the actual SQL statement text that matches the monitor rows to
the corresponding query. Only through SQL is the statement text captured. For queries executed using the
OPNQRYF command, the OPNID parameter is captured and can be used to tie the rows to the query. The
OPNID is contained in column Open_Id of row QQQ3014.

Queries with table scans example


Like the preceding example that showed which SQL applications were implemented with table scans, the
following example shows all queries that are implemented with table scans.

SELECT (D.End_Timestamp - D.Start_Timestamp) AS TOT_TIME, A.System_Table_Schema,


A.System_Table_Name,
A.Table_Total_Rows, A.Index_Advised,
B.Open_Id, B.Open_Time,
C.Clock_Time_to_Return_All_Rows, C.Number_Rows_Returned,
D.Result_Rows, D.Statement_Text_Long
FROM LIB.QQQ3000 A INNER JOIN LIB.QQQ3014 B
ON (A.Join_Column = B.Join_Column
LEFT OUTER JOIN LIB.QQQ3019 C
ON (A.Join_Column = C.Join_Column)
LEFT OUTER JOIN LIB.QQQ1000 D
ON (A.Join_Column = D.Join_Column)

In this example, the output for all queries that performed table scans are shown in the following table.
Note: The columns selected from table QQQ1000 do return NULL default values if the query was not
executed using SQL. For this example assume that the default value for character data is blanks and the
default value for numeric data is an asterisk (*).

150 IBM i: Performance and Query Optimization


Table 44. Output for All Queries that Performed Table Scans
ODP
Lib Table Total Index Query Open Clock Recs Rows TOT_
Name Name Rows Advised OPNID Time Time Rtned Rtned TIME Statement Text
LIB1 TBL1 20000 Y 1.1 4.7 10 10 6.2
SELECT *
FROM LIB1/TBL1
WHERE FLD1 = 'A'

LIB1 TBL2 100 N 0.1 0.7 100 100 0.9


SELECT *
FROM LIB1/TBL2

LIB1 TBL1 20000 Y 2.6 4.4 32 32 7.1


SELECT *
FROM LIB1/TBL1
WHERE FLD1 = 'A'
AND FLD2 > 9000

LIB1 TBL4 4000 N QRY04 1.2 4.2 724 * * *

If the SQL statement text is not needed, joining to table QQQ1000 is not necessary. You can determine
the total time and rows selected from data in the QQQ3014 and QQQ3019 rows.

Table scan detail example


Your next step could include further analysis of the table scan data. The previous examples contained a
column titled Index Advised. A 'Y' (yes) in this column is a hint from the query optimizer that the query
could perform better with an index to access the data. For the queries where an index is advised, the rows
selected by the query are low in comparison to the total number of table rows. This selectivity is another
indication that a table scan might not be optimal. Finally, a long execution time might highlight queries
that could be improved by performance tuning.
The next logical step is to look into the index advised optimizer hint. The following query can be used:

SELECT A.System_Table_Schema, A.System_Table_Name,


A.Index_Advised, A.Index_Advised_Columns,
A.Index_Advised_Columns_Count, B.Open_Id,
C.Statement_Text_Long
FROM LIB.QQQ3000 A INNER JOIN LIB.QQQ3014 B
ON (A.Join_Column = B.Join_Column)
LEFT OUTER JOIN LIB.QQQ1000 C
ON (A.Join_Column = C.Join_Column)
WHERE A.Index_Advised = 'Y'

There are two slight modifications from the first example. First, the selected columns have been changed.
Most important is the selection of Index_Advised_Columns containing a list of possible key columns to
use when creating the suggested index. Second, the query selection limits the output to those table scan
queries where the optimizer advises that an index is created (A.Index_Advised = 'Y'). The following table
shows what the results might look like.

Table 45. Output with Recommended Key Columns


Advised Advised
Lib Table Index Key Primary Query
Name Name Advised columns Key OPNID Statement Text
LIB1 TBL1 Y FLD1 1
SELECT * FROM LIB1/TBL1
WHERE FLD1 = 'A'

LIB1 TBL1 Y FLD1, 1


SELECT * FROM LIB1/TBL1
FLD2 WHERE FLD1 = 'B' AND
FLD2 > 9000

Database performance and query optimization 151


Table 45. Output with Recommended Key Columns (continued)
Advised Advised
Lib Table Index Key Primary Query
Name Name Advised columns Key OPNID Statement Text
LIB1 TBL4 Y FLD1, 1 QRY04
FLD4

Determine whether it makes sense to create a permanent index as advised by the optimizer. In this
example, creating one index over LIB1/TBL1 satisfies all three queries since each use a primary or
left-most key column of FLD1. By creating one index over LIB1/TBL1 with key columns FLD1, FLD2, there
is potential to improve the performance of the second query even more. Consider how often these queries
are run and the overhead of maintaining an additional index over the table when deciding whether to
create the suggested index.
If you create a permanent index over FLD1, FLD2 the next sequence of steps is as follows:
1. Start the performance monitor again
2. Rerun the application
3. End the performance monitor
4. Re-evaluate the data.
It is likely that the three index-advised queries are no longer performing table scans.

Additional database monitor examples


The following are additional ideas or examples on how to extract information from the performance
monitor statistics. All the examples assume that data has been collected in LIB/PERFDATA and the
documented views have been created.
1. How many queries are performing dynamic replans?

SELECT COUNT(*)
FROM LIB.QQQ1000
WHERE Dynamic_Replan_Reason_Code <> 'NA'

2. What is the statement text and the reason for the dynamic replans?

SELECT Dynamic_Replan_Reason_Code, Statement_Text_Long


FROM LIB.QQQ1000
WHERE Dynamic_Replan_Reason_Code <> 'NA'

Note: You need to refer to the description of column Dynamic_Replan_Reason_Code for definitions of
the dynamic replan reason codes.
3. How many indexes have been created over LIB1/TBL1?

SELECT COUNT(*)
FROM LIB.QQQ3002
WHERE System_Table_Schema = 'LIB1'
AND System_Table_Name = 'TBL1'

4. What key columns are used for all indexes created over LIB1/TBL1 and what is the associated SQL
statement text?

SELECT A.System_Table_Schema, A.System_Table_Name,


A.Index_Advised_Columns, B.Statement_Text_Long
FROM LIB.QQQ3002 A, LIB.QQQ1000 B
WHERE A.Join_Column = B.Join_Column
AND A.System_Table_Schema = 'LIB1'
AND A.System_Table_Name = 'TBL1'

Note: This query shows key columns only from queries executed using SQL.
5. What key columns are used for all indexes created over LIB1/TBL1 and what was the associated SQL
statement text or query open ID?

152 IBM i: Performance and Query Optimization


SELECT A.System_Table_Schema, A.System_Table_Name, A.Index_Advised_Columns,
B.Open_Id, C.Statement_Text_Long
FROM LIB.QQQ3002 A INNER JOIN LIB.QQQ3014 B
ON (A.Join_Column = B.Join_Column)
LEFT OUTER JOIN LIB.QQQ1000 C
ON (A.Join_Column = C.Join_Column)
WHERE A.System_Table_Schema LIKE '%'
AND A.System_Table_Name = '%'

Note: This query shows key columns from all queries on the system.
6. What types of SQL statements are being performed? Which are performed most frequently?

SELECT CASE Statement_Function


WHEN 'O' THEN 'Other'
WHEN 'S' THEN 'Select'
WHEN 'L' THEN 'DDL'
WHEN 'I' THEN 'Insert'
WHEN 'U' THEN 'Update'
ELSE 'Unknown'
END, COUNT(*)
FROM LIB.QQQ1000
GROUP BY Statement_Function
ORDER BY 2 DESC

7. Which SQL queries are the most time consuming? Which user is running these queries?

SELECT (End_Timestamp - Start_Timestamp), Job_User,


Current_User_Profile, Statement_Text_Long
FROM LIB.QQQ1000
ORDER BY 1 DESC

8. Which queries are the most time consuming?

SELECT (A.Open_Time + B.Clock_Time_to_Return_All_Rows),


A.Open_Id, C.Statement_Text_Long
FROM LIB.QQQ3014 A LEFT OUTER JOIN LIB.QQQ3019 B
ON (A.Join_Column = B.Join_Column)
LEFT OUTER JOIN LIB.QQQ1000 C
ON (A.Join_Column = C.Join_Column)
ORDER BY 1 DESC

Note: This example assumes that detail data was collected (STRDBMON TYPE(*DETAIL)).
9. Show the data for all SQL queries with the data for each SQL query logically grouped.

SELECT A.*
FROM LIB.PERFDATA A, LIB.QQQ1000 B
WHERE A.QQJFLD = B.Join_Column

Note: This might be used within a report that will format the interesting data into a more readable
format. For example, all reason code columns can be expanded by the report to print the definition of
the reason code. Physical column QQRCOD = 'T1' means that a table scan was performed because no
indexes exist over the queried table.
10. How many queries are implemented with temporary tables because a key length greater than 2000
bytes, or more than 120 key columns was specified for ordering?

SELECT COUNT(*)
FROM LIB.QQQ3004
WHERE Reason_Code = 'F6'

11. Which SQL queries were implemented with nonreusable ODPs?

SELECT B.Statement_Text_Long
FROM LIB.QQQ3010 A, LIB.QQQ1000 B
WHERE A.Join_Column = B.Join_Column
AND A.ODP_Implementation = 'N';

12. What is the estimated time for all queries stopped by the query governor?

Database performance and query optimization 153


SELECT Estimated_Processing_Time, Open_Id
FROM LIB.QQQ3014
WHERE Stopped_By_Query_Governor = 'Y'

Note: This example assumes that detail data was collected (STRDBMON TYPE(*DETAIL)).
13. Which queries estimated time exceeds actual time?

SELECT A.Estimated_Processing_Time,
(A.Open_Time + B.Clock_Time_to_Return_All_Rows),
A.Open_Id, C.Statement_Text_Long
FROM LIB.QQQ3014 A LEFT OUTER JOIN LIB.QQQ3019 B
ON (A.Join_Column = B.Join_Column)
LEFT OUTER JOIN LIB.QQQ1000 C
ON (A.Join_Column = C.Join_Column)
WHERE A.Estimated_Processing_Time/1000 >
(A.Open_Time + B.Clock_Time_to_Return_All_Rows)

Note: This example assumes that detail data was collected (STRDBMON TYPE(*DETAIL)).
14. Should you apply a PTF for queries containing UNIONs? Yes, if any queries are performing UNIONs.
Do any of the queries perform this function?

SELECT COUNT(*)
FROM QQQ3014
WHERE Has_Union = 'Y'

Note: If the result is greater than 0, apply the PTF.


15. You are a system administrator and an upgrade to the next release is planned. You want to compare
data from the two releases.
• Collect data from your application on the current release and save this data in LIB/CUR_DATA
• Move to the next release
• Collect data from your application on the new release and save this data in a different table: LIB/
NEW_DATA
• Write a program to compare the results. You need to compare the statement text between the rows
in the two tables to correlate the data.

Using System i Navigator with detailed monitors


You can work with detailed monitors from the System i Navigator interface. The detailed SQL performance
monitor is the System i Navigator version of the STRDBMON database monitor, found on the native
interface.
You can start this monitor by right-clicking SQL Performance Monitors under the Database portion of the
System i Navigator tree and selecting New > Monitor. This monitor saves detailed data in real time to a
hard disk. It does not need to be paused or ended in order to analyze the results. You can also choose to
run a Visual Explain based on the data gathered by the monitor. Since this monitor saves data in real time,
it might have a performance impact on your system.

Starting a detailed monitor


You can start a detailed monitor from the System i Navigator interface.
You can start this monitor by right-clicking SQL Performance Monitors under the Database portion of the
System i Navigator tree and selecting New > SQL Performance Monitor.
When you create a detailed monitor, you can filter the information that you want to capture.

Initial number Select to specify the number of records initially allocated for the monitor. The 'Initial
of records: number of records' option is used to pre-allocate storage to the database monitor
out file. When collecting large amounts of monitor records, this option improves the
collection performance by avoiding automatic storage extensions that occur as a file
grows in size.

154 IBM i: Performance and Query Optimization


Minimum Select to include queries that exceed a specified amount of time. Select a number and
estimated then a unit of time.
query runtime:
Minimum Select to include queries that exceed a certain amount of temporary storage. Specify a
estimated size in MB.
temporary
storage:
Job name: Select to filter by a specific job name. Specify a job name in the field. You can specify
the entire ID or use a wildcard. For example, 'QZDAS*' finds all jobs where the name
starts with 'QZDAS.'
Job user: Select to filter by a job user. Specify a user ID in the field. You can specify the entire ID
or use a wildcard. For example, 'QUSER*' finds all user IDs where the name starts with
'QUSER.'
Current user: Select to filter by the current user of the job. Specify a user ID in the field. You can
specify the entire ID or use a wildcard. For example, 'QSYS*' finds all users where the
name starts with 'QSYS.'
Client Select to filter by Internet access. The input needs to be in IPv4 or IPv6 form.
location:
1. IP version 4 address in dotted decimal form. Specify an Internet Protocol version
4 address in the form nnn.nnn.nnn.nnn where each nnn is a number in the range 0
through 255.
2. IP version 6 address in colon hexadecimal form. Specify an internet protocol version
6 address in the form xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx, where each xxxx is
a hex number in the range 0 through FFFF. IP version 6 includes the IPv4-mapped
IPv6 address form (for example, ::FFFF:1.2.3.4). For IP version 6, the compressed
form of the address is allowed.
3. IP host domain name. Specify an internet host domain name of up to 254 characters
in length.

Local port: Select to filter by port number. You can select a port from the list or else enter your own
port number.
Ports in the list include:
• 446 - DRDA/DDM
• 447 - DRDA/DDM
• 448 - Secure DRDA/DDM (SSL)
• 4402 - QXDAEDRSQL server
• 8471 - Database server
• 9471 - Secure database server (SSL)

Query Select to search for queries that have exceeded or are expected to exceed the query
Governor governor limits set for the system. Choose from the following options:
limits:
• Always collect information when exceeded
• Conditional collection of information when exceeded

Client Select to filter by the client register information.


registers:
Statements Select to filter by only queries that use certain tables. Click Browse to select tables to
that access include. To remove a table from the list, select the table and click Remove. A maximum
these objects: of 10 table names can be specified.
Activity to Select to collect monitor output for user-generated queries or for both user-generated
monitor: and system-generated queries.

Database performance and query optimization 155


You can choose which jobs you want to monitor or choose to monitor all jobs. You can have multiple
instances of monitors running on your system at one time. You can create up to 10 detailed monitors to
monitor all jobs. When collecting information for all jobs, the monitor will collect on previously started
jobs or new jobs that are started after the monitor is created. You can edit this list by selecting and
removing jobs from the Selected jobs list.

Analyzing detailed monitor data


SQL performance monitors provides several predefined reports that you can use to analyze your monitor
data.
To view these reports, right-click a monitor and select Analyze. The monitor does not need to be ended in
order to view this information.

On the Analysis Overview dialog, you can view overview information or else choose one of the following
categories:
• How much work was requested?
• What options were provided to the optimizer?
• What implementations did the optimizer use?
• What types of SQL statements were requested?
• Miscellaneous information
• I/O information
From the Actions menu, you can choose one of the following summary predefined reports:

User Contains a row of summary information for each user. Each row summarizes all SQL
summary activity for that user.

156 IBM i: Performance and Query Optimization


Job Contains a row of information for each job. Each row summarizes all SQL activity for
summary that job. This information can be used to tell which jobs on the system are the heaviest
users of SQL. These jobs are perhaps candidates for performance tuning. You could then
start a separate detailed performance monitor on an individual job to get more detailed
information without having to monitor the entire system.
Operation Contains a row of summary information for each type of SQL operation. Each row
summary summarizes all SQL activity for that type of SQL operation. This information provides
the user with a high-level indication of the type of SQL statements used. For example, are
the applications mostly read-only, or is there a large amount of update, delete, or insert
activity. This information can then be used to try specific performance tuning techniques.
For example, if many INSERTs are occurring, you might use an OVRDBF command to
increase the blocking factor or the QDBENCWT API.
Program Contains a row of information for each program that performed SQL operations. Each row
summary summarizes all SQL activity for that program. This information can be used to identify
which programs use the most or most expensive SQL statements. Those programs are
then potential candidates for performance tuning. A program name is only available if
the SQL statements are embedded inside a compiled program. SQL statements that are
issued through ODBC, JDBC, or OLE DB have a blank program name unless they result
from a procedure, function, or trigger.

In addition, when a green check is displayed under Summary column, you can select that row and click
Summary to view information about that row type. Click Help for more information about the summary
report. To view information organized by statements, click Statements.

Comparing monitor data


You can use System i Navigator to compare data sets in two or more monitors.
System i Navigator provides you with two types of comparison. The first is a simple compare that provides
a high-level comparison of the monitors or snapshots. The second is a detailed comparison. The simple
compare provides you with enough data about the monitors or snapshots to help you determine if a
detailed comparison is helpful.
To launch a simple compare, go to System i Navigator > system name > SQL performance monitors.
Right-click one or more monitors and select Compare.
To launch a detailed comparison, select the Detailed Comparison tab.
On the Detailed Comparison dialog, you can specify information about the data sets that you want to
compare.

Name The name of the monitors that you want to compare.


Schema mask Select any names that you want the comparison to ignore. For example, consider
the following scenario: You have an application running in a test schema and it is
optimized. Now you move it to the production schema and you want to compare
how it executes there. The statements in the comparison are identical except that
the statements in the test schema use "TEST" and the statements in the production
schema use "PROD". You can use the schema mask to ignore "TEST" in the first
monitor and "PROD" in the second monitor. Then the statements in the two monitors
appear identical.
Statements that The minimum runtime for statements to be compared.
ran longer than
Minimum The minimum difference in key attributes of the two statements being compared
percent that determines if the statements are considered equal or not. For example, if you
difference select 25% as the minimum percent different, only matching statements whose key
attributes differ by 25% or more are returned.

Database performance and query optimization 157


When you click Compare, both monitors are scanned for matching statements. Any matches found are
displayed side-by-side for comparison of key attributes of each implementation.
On the Comparison output dialog, you view statements that are included in the monitor by clicking Show
Statements. You can also run Visual Explain by selecting a statement and clicking Visual Explain.
Any matches found are displayed side-by-side for comparison of key attributes of each implementation.

Viewing statements in a monitor


You can view SQL statements that are included in a detailed monitor.
Right-click any detailed monitor in the SQL performance monitor window and select Show statements.
The filtering options provide a way to focus in on a particular area of interest:

Minimum runtime for the Select to include statements that exceed a certain amount of time.
longest execution of the Select a number and then a unit of time.
statement:
Statements that ran on or Select to include statements run at a specified date and time. Select a
after this date and time: date and time.
Statements that reference Select to include statements that use or reference certain objects. Click
the following objects: Browse to select objects to include.
Statements that contain the Select to include only those statements that contain a specific type of
following text: SQL statement. For example, specify SELECT if you only want to include
statements that are using SELECT. The search is case insensitive for
ease of use. For example, the string 'SELECT' finds the same entries as
the search string 'select'.

Multiple filter options can be specified. In a multi-filter case, the candidate entries for each filter are
computed independently. Only those entries that are present in all the candidate lists are shown. For
example, if you specified options Minimum runtime for the longest execution of the statement and
Statements that ran on or after this date and time, you will be shown statements with the minimum
runtime that ran on or after the specified date and time.
Related reference
Index advisor
The query optimizer analyzes the row selection in the query and determines, based on default values, if
creation of a permanent index improves performance. If the optimizer determines that a permanent index
might be beneficial, it returns the key columns necessary to create the suggested index.

Importing a monitor
You can import monitor data that has been collected using some other interface by using System i
Navigator.
Monitors that are created using the Start Database Monitor (STRDBMON) command are
automatically registered with System i Navigator. They are also included in the list of monitors displayed
by System i Navigator.
To import monitor data, right-click SQL Performance monitors and select Import. Once you have
imported a monitor, you can analyze the data.

Index advisor
The query optimizer analyzes the row selection in the query and determines, based on default values, if
creation of a permanent index improves performance. If the optimizer determines that a permanent index
might be beneficial, it returns the key columns necessary to create the suggested index.
The optimizer is able to perform radix index probe over any combination of the primary key columns, plus
one additional secondary key column. Therefore it is important that the first secondary key column is

158 IBM i: Performance and Query Optimization


the most selective secondary key column. The optimizer uses radix index scan with any of the remaining
secondary key columns. While radix index scan is not as fast as radix index probe, it can still reduce the
number of keys selected. It is recommended that secondary key columns that are fairly selective are
included.
Determine the true selectivity of any secondary key columns and whether you include those key columns
in the index. When building the index, make the primary key columns the left-most key columns, followed
by any of the secondary key columns chosen, prioritized by selectivity.
After creating the suggested index and executing the query again, it is possible that the query optimizer
will choose not to use the suggested index. It does not include join, ordering, and grouping criteria. The
SQE optimizer includes selection, join, ordering, and grouping criteria when suggesting indexes. Local
selection advice can now factor in both AND and OR predicates with the qualifications mentioned below.
You can access index advisor information in many different ways. These ways include:
• The index advisor interface in System i Navigator
• SQL performance monitor Show statements
• Visual Explain interface
• Querying the Database monitor view 3020 - Index advised.
Related reference
Overview of information available from Visual Explain
You can use Visual Explain to view many types of information.
Database monitor view 3020 - Index advised (SQE)
Displays the SQL logical view format for database monitor QQQ3020.
Viewing statements in a monitor
You can view SQL statements that are included in a detailed monitor.

Index advice and OR predicates


Index advice generation to handle OR predicates
Index Advisor has been extended to include queries that OR together local selection (WHERE clause)
columns over a single table. OR advice requires two or more indexes to be created as a dependent set.
If any of the OR'd indexes are missing, the optimizer won’t be able to cost and choose these dependent
indexes for implementation of the OR based query.
This relationship between OR based indexes in the SYSIXADV index advice table is with a new
DEPENDENT_ADVICE_COUNT column.
Some restrictions with this support:
• OR'd predicate advice appears only if no other advice is generated
• Maximum of 5 predicates OR'd together
• Advised for files with OR'd local selection that get costed in the primary join dial when optimizing a join
query
When Index Advisor shows highly dependent advice, use of the exact match capability from Show
Statements to find the query in the plan cache is helpful. Once found, use Visual Explain to discover
the dependent index advice specific to that query.

Index Or Advice example


• Should advise indexes over all OR'd predicate columns
• All 3 advised indexes will have DEPENDENT_ADVICE_COUNT>0
• Execution with indexes should produce bitmap implementation and register no new advice

SELECT orderkey, partkey, suppkey,


linenumber, shipmode orderpriority

Database performance and query optimization 159


FROM item_fact
WHERE OrderKey <= 10 OR
SuppKey <= 10 OR
PartKey <= 10
OPTIMIZE FOR ALL ROWS

The graphic below shows the Index advice for the OR'd predicate columns:

The graphic below depicts the Visual Explain showing the implementation of merge bitmap
representation using the OR'd advice indexes:

160 IBM i: Performance and Query Optimization


Index advice for Encoded Vector Index RRN Probe Plans
Indexes are not advised for use by Encoded Vector Index RRN Probe Plans.
Indexes are not advised for use by Encoded Vector Index RRN Probe Plans.

Displaying index advisor information


You can display index advisor information from the optimizer using System i Navigator.
System i Navigator displays information found in the QSYS2/SYSIXADV system table.
To display index advisor information, follow these steps:
1. In the System i Navigator window, expand the system that you want to use.
2. Expand Databases.
3. Right-click the database that you want to work with and select Index Advisor > Index Advisor.

Database performance and query optimization 161


You can also find index advisor information for a specific schema or a specific table by right-clicking on a
schema or table object.
Once you have displayed the information, you have several options. You can create an index from the list,
remove the index advised from the list, or clear the list entirely. You can also right-click on an index and
select Show SQL, launching a Run SQL Scripts session with the index creation statement. Finally, you can
right-click on an advised index and select Show Statements. With additional information automatically
provided in the advised index filter for the Plan Cache search, the resulting SQL statements shown will be
a better match to the original queries that generated that specific index advice.
Depending on if you are viewing the index advice at the database level or the schema level your list could
be large. Once you have the list displayed, follow these steps to subset your list:
1. Go to the View menu option, and select Customize this view > Include ....
2. Enter the information you would like to filter the list by.
3. Press the OK button to get the refreshed list of index advice.

Database manager indexes advised system table


This topic describes the indexes advised system table.

Table 46. SYSIXADV system table


Column name System Data type Description
column name
TABLE_NAME TBNAME VARCHAR(258) Table over which an index is advised
TABLE_SCHEMA DBNAME VARCHAR(128) SQL schema containing the table
SYSTEM_TABLE_NAME SYS_TNAME CHAR(10) System table name on which the index
is advised
PARTITION_NAME TBMEMBER CHAR(10) Partition detail for the index
KEY_COLUMNS_ADVISED KEYSADV VARCHAR(1600 Column names for the advised index
0)
LEADING_COLUMN_KEYS LEADKEYS VARCHAR(1600 Leading, Order Independent keys.
0) the keys at the beginning of the
KEY_COLUMNS_ADVISED field which
could be reordered and still satisfy the
index being advised.
INDEX_TYPE INDEX_TYPE CHAR(14) Radix (default) or EVI
LAST_ADVISED LASTADV TIMESTAMP Last time this row was updated
TIMES_ADVISED TIMESADV BIGTINT Number of times this index has been
advised
ESTIMATED_CREATION_TIM ESTTIME INT Estimated number of seconds for
E index creation
REASON_ADVISED REASON CHAR(2) Coded reason why index was advised
LOGICAL_PAGE_SIZE PAGESIZE INT Recommended page size for index
MOST_EXPENSIVE_QUERY QUERYCOST INT Execution time in seconds of the query
AVERAGE_QUERY_ESTIMATE QUERYEST INT Average execution time in seconds of
the query
TABLE_SIZE TABLE_SIZE BIGINT Number of rows in table when the
index was advised

162 IBM i: Performance and Query Optimization


Table 46. SYSIXADV system table (continued)
Column name System Data type Description
column name
NLSS_TABLE_NAME NLSSNAME CHAR(10) NLSS table to use for the index
NLSS_TABLE_SCHEMA NLSSDBNAM CHAR(10) Schema name of the NLSS table
E
MTI_USED MTIUSED BIGINT The number of times that this specific
Maintained Temporary Index (MTI)
has been used by the optimizer. The
optimizer stops using a matching MTI
once a permanent index is created.
MTI_CREATED MTICREATED INTEGER The number of times that this specific
Maintained Temporary Index (MTI) has
been created by the optimizer. MTIs do
not persist across system IPLs.
LAST_MTI_USED LASTMTIUSE TIMESTAMP The timestamp representing the
last time this specific Maintained
Temporary Index (MTI) was used
by the optimizer to improve the
performance of a query. The MTI
Last Used field can be blank. The
blank field indicates that an MTI
which exactly matches this advice has
never been used by the queries which
generated this index advice.
AVERAGE_QUERY_ESTIMATE QRYMICRO BIGINT Average execution time in
_MICRO microseconds of the query which
drove the index advice
EVI_DISTINCT_VALUES EVIVALS INTEGER Recommended value to use when
creating the advised EVI index. This
value is n within the WITH n DISTINCT
VALUES clause on the CREATE INDEX
SQL statement.
INCLUDE_COLUMNS INCLCOL CLOB(10000) EVI INCLUDE expressions for index
creation.
FIRST_ADVISED FIRSTADV TIMESTAMP When this row was inserted.
SYSTEM_TABLE_SCHEMA SYS_DNAME CHAR(10) System name of the table schema.
MTI_USED_FOR_STATS MTISTATS BIGINT Number of times Maintained
Temporary Index was used as a source
for optimizer statistics.
LAST_MTI_USED_FOR_STATS LASTMTISTA TIMESTAMP The timestamp representing the
last time this specific Maintained
Temporary Index was used as a
source of statistics by the optimizer to
improve the performance of a query.
DEPENDENT_ADVICE_COUN DEPCNT BIGINT The number of times this index advice
T was dependent upon other advice.

Database performance and query optimization 163


Index advisor column descriptions
Displays the columns that are used in the Index advisor window.

Table 47. Columns used in Index advisor window


Column name Description
Table for Which Index was Advised The optimizer is advising creation of a permanent index over
this table. This value is the long name for the table. The
advice was generated because the table was queried and
no existing permanent index could be used to improve the
performance of the query.
Schema Schema or library containing the table.
System Schema System name of the schema.
System Name System table name on which the index is advised
Partition Partition detail for the index. Possible values:
• <blank>, which means For all partitions
• For Each Partition
• specific name of the partition

Keys Advised Column names for the advised index. The order of the
column names is important. The names are listed in the
same order as in the CREATE INDEX SQL statement. An
exception is when the leading, order independent key
information indicates that the ordering can be changed.
Leading Keys Order Independent Leading, Order Independent keys. the keys at the beginning
of the KEY_COLUMNS_ADVISED field which could be
reordered and still satisfy the index being advised.
Index Type Advised Radix (default) or EVI
Last Advised for Query Use The timestamp representing the last time this index was
advised for a query.
Times Advised for Query Use The cumulative number of times this index has been advised.
This count ceases to increase once a matching permanent
index is created. The row of advice remains in this table until
the user removes it
Estimated Index Creation Time Estimated time in seconds to create this index.
Reason advised Reason why index was advised. Possible values are:
Row selection
Ordering/Grouping
Row selection and Ordering/Grouping

Logical Page Size Advised (KB) Recommended page size to be used on the PAGESIZE
keyword of the CREATE INDEX SQL statement when creating
this index.
Most Expensive Query Estimate Execution time in seconds of the longest running query
which generated this index advice.
Average of Query Estimates Average execution time in seconds of all queries that
generated this index advice.

164 IBM i: Performance and Query Optimization


Table 47. Columns used in Index advisor window (continued)
Column name Description
Rows in Table when Advised Number of rows in table for the last time this index was
advised.
NLSS Table Advised The sort sequence table in use by the query which generated
the index advice. For more detail on sort sequences:
NLSS Schema Advised The schema of the sort sequence table.
MTI Used The number of times that this specific Maintained Temporary
Index (MTI) has been used by the optimizer.
MTI Created The number of times that this specific Maintained Temporary
Index (MTI) has been created by the optimizer. MTIs do not
persist across system IPLs.
MTI Last Used The timestamp representing the last time this specific
Maintained Temporary Index (MTI) was used by the
optimizer to improve the performance of a query. The MTI
Last Used field can be blank. A blank field indicates that an
MTI which exactly matches this advice has never been used
by the queries which generated this index advice.
EVI Distinct Values Recommended value to use when creating the advised EVI
index. This value is n within the WITH n DISTINCT VALUES
clause on the CREATE INDEX SQL statement.
First Advised The date/time when a row is first added to the Index Advisor
table for this advice.
MTI Used for Stats The number of times that this specific Maintained Temporary
Index (MTI) has been used by the optimizer.
MTI Last Used for Stats The timestamp representing the last time this specific
Maintained Temporary Index (MTI) was used as a source of
statistics by the optimizer to improve the performance of a
query. The MTI Last Used field can be blank.
Dependent Advice Count Dependent implies that this advised index is dependent on
the creation of other dependent advised indexes and all of
the other dependent indexes must be created in order for the
index implementation to be costed and utilized.
• Zero - this advised index stands on its own.
• Greater than Zero – Compare this column against the
TIMES_ADVISED column to understand how often this
advised index has been advised in conjunction with other
indexes.

Querying database monitor view 3020 - Index advised


The index advisor information can be found in the Database Monitor view 3020 - Index advised (SQE).
The advisor information is stored in columns QQIDXA, QQIDXK, and QQIDXD. When the QQIDXA column
contains a value of 'Y' the optimizer is advising you to create an index using the key columns shown in
column QQIDXD. The intention of creating this index is to improve the performance of the query.
In the list of key columns contained in column QQIDXD, the optimizer has listed what it considers the
suggested primary and secondary key columns. Primary key columns are columns that can significantly

Database performance and query optimization 165


reduce the number of keys selected based on the corresponding query selection. Secondary key columns
are columns that might or might not significantly reduce the number of keys selected.
Column QQIDXK contains the number of suggested primary key columns that are listed in column
QQIDXD. These primary key columns are the left-most suggested key columns. The remaining key
columns are considered secondary key columns and are listed in order of expected selectivity based
on the query. For example, assuming QQIDXK contains the value of four and QQIDXD specifies seven key
columns, then the first four key columns are the primary key columns. The remaining three key columns
are the suggested secondary key columns.

Condensing index advice


Many times, the index advisor advises several different indexes for the same table. You can condense
these advised indexes into the best matches for your queries.
1. In the System i Navigator window, expand the system you want to use.
2. Expand Databases.
3. Right-click the database that you want to work with and select Index Advisor > Condense Advised
Indexes.
Depending on if you are viewing the condensed index advice at the database level or the schema level
your list could be large. Once you have the list displayed, follow these steps to subset your list:
1. Go to the View menu option, and select Customize this view > Include ...
2. Enter the information you would like to filter the list by.
3. Select OK to get the refreshed list of condensed index advice.

Viewing your queries with Visual Explain


You can use the Visual Explain tool with System i Navigator to create a query graph that graphically
displays the implementation of an SQL statement. You can use this tool to see information about both
static and dynamic SQL statements. Visual Explain supports the following types of SQL statements:
SELECT, INSERT, UPDATE, and DELETE.
Queries are displayed using a graph with a series of icons that represent different operations that occur
during implementation. This graph is displayed in the main window. In the lower portion of the pane, the
SQL statement that the graph is based on is displayed. If Visual Explain is started from Run SQL Scripts,
you can view the debug messages issued by the optimizer by clicking the Optimizer messages tab. The
query attributes are displayed in the right pane.
Visual Explain can be used to graphically display the implementations of queries stored in the detailed
SQL performance monitor. However, it does not work with tables resulting from the memory-resident
monitor.

Starting Visual Explain


There are two ways to invoke the Visual Explain tool. The first, and most common, is through System i
Navigator. The second is through the Visual Explain (QQQVEXPL) API.
You can start Visual Explain from any of the following windows in System i Navigator:
• Enter an SQL statement in the Run SQL Scripts window. Select the statement and choose Explain or
Run and Explain from the Visual Explain menu.

166 IBM i: Performance and Query Optimization


• Expand the list of available SQL Performance Monitors. Right-click a detailed SQL Performance Monitor
and choose the Show Statements option. Select filtering information and select the statement in
the List of Statements window. Right-click and select Visual Explain. You can also start an SQL
Performance Monitor from Run SQL Scripts. Select Start SQL Performance monitor from the Monitor
menu.
• Start the SQL Details for Jobs function by right-clicking Databases and select SQL Details for Jobs.
Click Apply. Select a job from the list and right-click and select Show Details. When the SQL is
displayed in the lower pane, you can start Visual Explain by right-clicking on Statement and selecting
Visual Explain.
• Right-click SQL Plan Cache and select Show Statements. Select filtering information and select the
statement in the List of Statements window. Right-click and select Visual Explain.
• Expand the list of available SQL Plan Cache Snapshots. Right-click a snapshot and select Show
Statements. Select filtering information and select the statement in the List of Statements window.
Right-click and select Visual Explain.
• Expand the list of SQL Plan Cache Event Monitors. Right-click an event monitor and select Show
Statements. Select filtering information and select the statement in the List of Statements window.
Right-click and select Visual Explain.
You have three options when running Visual Explain from Run SQL Scripts.

Visual This option allows you to explain the query without actually running it. The data
Explain only displayed represents the estimate of the query optimizer.
Note: Some queries might receive an error code 93 stating that they are too complex
for displaying in Visual Explain. You can circumvent this error by selecting the "Run and
Explain" option.

Run and If you select Run and Explain, the query is run by the system before the diagram is
Explain displayed. This option might take a significant amount of time, but the information
displayed is more complete and accurate.
Explain while For long running queries, you can choose to start Visual Explain while the query is
running running. By refreshing the Visual Explain diagram, you can view the progress of the
query.

In addition, a database monitor table that was not created as a result of using System i Navigator can
be explained through System i Navigator. First you must import the database monitor table into System i
Navigator. To import, right-click the SQL Performance Monitors and choose the Import option. Specify a
name for the performance monitor (name it is known by within System i Navigator) and the qualified name
of the database monitor table. Be sure to select Detailed as the type of monitor. Detailed represents the
file-based (STRDBMON) monitor while Summary represents the memory-resident monitor (which is not
supported by Visual Explain). Once the monitor has been imported, follow the steps to start Visual Explain
from within System i Navigator.
You can save your Visual Explain information as an SQL Performance monitor. This monitor can be useful
if you started the query from Run SQL Scripts and want to save the information for later comparison.
Select Save as Performance monitor from the File menu.
Related information
Visual Explain (QQQVEXPL) API

Overview of information available from Visual Explain


You can use Visual Explain to view many types of information.
The information includes:
• Information about each operation (icon) in the query graph
• Highlight expensive icons
• The statistics and index advisor

Database performance and query optimization 167


• The predicate implementation of the query
• Basic and detailed information in the graph

Information about each operation (icon) in the query graph


As stated before, the icons in the graph represent operations that occur during the implementation of
the query. The order of operations is shown by the arrows connecting the icons. If parallelism was used
to process an operation, the arrows are doubled. Occasionally, the optimizer "shares" hash tables with
different operations in a query, causing the lines of the query to cross.
You can view information about an operation by selecting the icon. Information is displayed in the
Attributes table in the right pane. To view information about the environment, click an icon and then
select Display query environment from the Action menu. Finally, you can view more information about
the icon by right-clicking the icon and selecting Help.

Highlight expensive icons


You can highlight problem areas (expensive icons) in your query using Visual Explain. Visual Explain offers
you two types of expensive icons to highlight: by processing time or number of rows. You can highlight
icons by selecting Highlight expensive icons from the View menu.

The statistics and index advisor


During the query implementation, the optimizer can determine if statistics need to be created or
refreshed, or if an index might make the query run faster. You can view these recommendations using
the Statistics and Index Advisor from Visual Explain. Start the advisor by selecting Advisor from the
Action menu. Additionally, you can begin collecting statistics or create an index directly from the advisor.

The predicate implementation of the query


Visual explain allows you to view the implementation of query predicates. Predicate implementation is
represented by a blue plus sign next to an icon. You can expand this view by right-clicking the icon and
selecting Expand. or open it into another window. Click an icon to view attributes about the operation. To
collapse the view, right-click anywhere in the window and select Collapse. This function is only available
on V5R3 or later systems.
The optimizer can also use the Look Ahead Predicate Generation to minimize the random the I/O costs of
a join. To highlight predicates that used this method, select Highlight LPG from the View menu.

Basic and full information in the graph


Visual Explain also presents information in two different views: basic and full. The basic view only shows
those icons that are necessary to understand the implementation of the SQL statement. It excludes some
preliminary, or intermediate operations that are not essential for understanding the main flow of query
implementation. The full view might show more icons that further depict the flow of the execution tree.
You can change the graph detail by select Graph Detail from the Options menu and selecting either Basic
or Full. The default view is Basic. In order to see all the detail for a Full view, change the Graph Detail to
Full, close out Visual Explain, and run the query again. The setting for Graph Detail persists.
For more information about Visual Explain and the different options that are available, see the Visual
Explain online help.

Refresh the Visual Explain diagram


For long running queries, you can refresh the visual explain graph with runtime statistical information
before the query is complete. Refresh also updates the appropriate information in the attributes section of
the icon shown on the right of the screen. In order to use the Refresh option, you need to select Explain
while Running from the Run SQL Scripts window.

168 IBM i: Performance and Query Optimization


To refresh the diagram, select Refresh from the View menu. Or click the Refresh button in the toolbar.
Related reference
Index advisor
The query optimizer analyzes the row selection in the query and determines, based on default values, if
creation of a permanent index improves performance. If the optimizer determines that a permanent index
might be beneficial, it returns the key columns necessary to create the suggested index.

Adaptive Query Processing in Visual Explain


You can use Visual Explain to request a new plan.
There might be times when you are asked to performance tune a query while the query is still running. For
instance, a query might be taking a long time to finish. After viewing the plan in Visual Explain, you decide
to create the recommended index to improve the speed of the query. So you create the index and then
want to signal the database optimizer to consider a new plan based on the new index.
Here are the steps to request the database engine to consider a new plan while running in Visual Explain:
1. Open Run SQL Scripts.
2. Type in a query.
3. Go to the Visual Explain menu and select Explain While Running.
4. The Visual Explain window is displayed.
5. Next, go to the Actions menu and select Request New Plan.

A message box appears.


Select Yes to restart the query.

Database performance and query optimization 169


The database optimizer considers any changes to the query environment, and determines whether it is
appropriate to generate a new plan. It might be possible that the database optimizer decides it is better to
continue using the existing plan.
Note: This capability could also be available when selecting Visual Explain of a statement in the SQL
Details for a Job window, or the SQL Plan Cache Show Statements window.
Related reference
Adaptive Query Processing
Adaptive Query Processing analyzes actual query run time statistics and uses that information for
subsequent optimizations.

Optimizing performance using the Plan Cache


The SQL Plan Cache contains a wealth of information about the SQE queries being run through the
database. Its contents are viewable through the System i Navigator GUI interface. Certain portions of the
plan cache can also be modified.
In addition, procedures are provided to allow users to programmatically work with the plan cache. These
procedures can be invoked using the SQL CALL statement.
The Plan Cache interface provides a window into the database query operations on the system. The
interface to the Plan Cache resides under the System i Navigator > system name > Database.
Within the SQL Plan Cache folder are two folders, SQL Plan Cache Snapshots and SQL Plan Cache Event
Monitors.
Clicking the SQL Plan Cache Snapshots folder shows a list of any snapshots gathered so far. A snapshot is
a database monitor file generated from the plan cache at the time a 'New Snapshot' is requested. It can
be treated much the same as the SQL Performance Monitors list. The same analysis capability exists for
snapshots as exists for traditional SQL performance monitors.
Clicking the SQL Plan Cache Event Monitors shows a list of any events that have been defined. Plan
Cache event monitors, when defined, generate database monitor information from plans as they are being
removed from the cache. The list includes currently active events as well as ones that have completed.
Like a snapshot, the event monitor is a database monitor file. Consequently, the same analysis capability
available to SQL performance monitors and snapshots can be used on the event file.
The plan cache is an actively changing cache. Therefore, it is important to realize that it contains timely
information. If information over long periods of time is of interest, an event monitor could be defined to
ensure that information is captured on any plans that are removed from the cache over time. Alternatively,
you could consider implementing a method of performing periodic snapshots of the plan cache to capture
trends and heavy usage periods. See the discussion on IBM supplied, callable SQL procedures later in this
section on plan cache.
Related concepts
Plan cache

170 IBM i: Performance and Query Optimization


The plan cache is a repository that contains the access plans for queries that were optimized by SQE.

SQL Plan Cache - Show Statements


By right-clicking the SQL Plan Cache icon, a series of options are shown which allow different views of
current plan cache of the database. The SQL Plan Cache > Show Statements option opens a screen with
filtering capability. This screen provides a direct view of the current plan cache on the system.

Press the Apply or Refresh button to display the current Plan Cache statements. The information shown
includes the SQL query text, last time the query ran, most expensive single instance run, total processing
time consumed, total number of times run, and information about the user and job that first created the
plan entry.
The information also includes several per run averages, including average runtime, average result set size
and average temporary storage usage. There is an adjusted average processing time which is the average
discounting any anomalous runs.

Database performance and query optimization 171


The display also shows how many times, if any, that the database engine resued the results of a prior run,
avoiding rerunning the entire statement. There is also a Save Results button (not shown) that allows you
to save the statement list, for example, to a .csv file or spreadsheet.
Finally, the numeric identifier and plan score are also displayed. For more detail on the columns
displayed, see “SQL Plan Cache column descriptions” on page 174

Statement Options
By highlighting one or more plans and right clicking, a menu with several possible actions appears.

Visual Explain Shows a visual depiction of the access plan and provides more detailed performance
analysis. Note only one statement can be highlighted when performing this action.

Show Shows details of up to 10 of the longest running instances of that statement. Within the
Longest Longest Runs list, you can right click a statement and select Visual Explain, Work With SQL
Runs Statement, Work With SQL Statement and Variables, Save to New... snapshot or Remove.
Snapshots are useful for capturing the information for that specific run in Visual Explain.
Removing old or superfluous runs makes room to capture future runs. Only one statement
can be highlighted when performing these actions. Any runs removed only affect which runs
are shown in the list. The total time, total number of runs, and other information for the
statement are still calculated including the runs removed from the list.

Show Active Jobs Displays a list of jobs on the system that are currently using that statement or
statements.

Show User History Shows a list of all user IDs that have run that statement along with the last time
they ran it.

Work with SQL Displays a scripting window containing the SQL statement. The scripting window
Statement is useful for working with and tuning the statement directly, or for just viewing
the statement in its own window. Only one statement can be highlighted when
performing this action.

Work with SQL Statements Displays a scripting window containing the SQL Statement and any
and Variables parameter markers entered with their specific values for that run of the
SQL statement.

Save to New... Allows you to create a snapshot of the selected statements.

Plan Right-click to show options for modifying the plan:


Change Plan Score allows you to set the score to a specific value. The plan score is used to
determine when a plan might be removed from the cache. A lower score plan is removed before a
higher score plan. By setting the plan score high, the plan remains in the cache for a longer time.
Setting the plan score to a low value causes the plan to be pruned sooner than might otherwise
have occurred.
Delete allows you to remove the plan immediately from the cache. Note under normal
circumstances there might not be a need to modify the attributes of a plan. Normal database
processing ages and prunes plans appropriately. These modifying options are provided mostly as
tools for minute analysis and for general interest.

The User and Job Name for each statement on the Statements screen is the user and job that created
the initial plan with full optimization. This user is not necessarily the same as the last user to run that
statement. The Longest Runs screen, however, does show the particular user and job for that individual
run.

172 IBM i: Performance and Query Optimization


Filtering Options
The screen provides filtering options which allow the user to more quickly isolate specific criteria of
interest. No filters are required to be specified (the default), though adding filtering shortens the time
it takes to show the results. The list of statements that is returned is ordered so that the statement
consuming the most total processing time is shown at the top. You can reorder the results by clicking the
column heading for which you want the list ordered. Repeated clicking toggles the order from ascending
to descending.
The filtering options provide a way to focus in on a particular area of interest:

Minimum runtime for the Show statements with at least one long individual statement instance
longest execution of the runtime.
statement:
Statements that ran on or Show statements that have been run recently.
after this date and time:
Top 'n' most frequently run Show statements run most often.
statements:
Top 'n' statements with the Show the top resource consumers. Shows the first 'n' top statements by
largest total accumulated default when no filtering is given. Specifying a value for 'n' improves the
runtime: performance of getting the first screen of statements, though the total
statements displayed is limited to 'n'.
Statements the following Show statements a particular user has run. The user and job name shown
user has ever run: reflect the originator of the cached statement. This user is not necessarily
the same as the user specified on the filter (there could be multiple users
running the statement).
Statements that are Show statements that are still running or are in pseudo-close mode. The
currently active user and job name shown reflect the originator of the cached statement.
This user is not necessarily the same as the user specified on the filter
(there could be multiple users running the statement).
Note: An alternative for viewing the active statement for a job is to right-
click the Database icon and select SQL Details for Jobs...

Statements for which an Show only those statements where the optimizer advised an index to
index has been advised improve performance.
Statements for which Show only those statements where a statistic not yet collected might have
statistics have been been useful to the optimizer. The optimizer automatically collects these
advised statistics in the background. This option is normally not that interesting
unless, for whatever reason, you want to control the statistics collection
yourself.
Include statements Show the 'hidden' statements initiated by the database to process a
initiated by the operating request. By default the list only includes user-initiated statements.
system
Statements that reference Show statements that reference the tables or indexes specified.
the following objects:
Statements that contain Show statements that include the text specified. This option is useful
the following text: for finding particular types of statements. For example, statements with
a FETCH FIRST clause can be found by specifying ‘fetch'. The search is
not case sensitive for ease of use. For example, the string 'FETCH' finds
the same statements as the search string 'fetch'. This option provides a
wildcard search capability on the SQL text itself.

Multiple filter options can be specified. The candidate statements for each filter are computed
independently. Only those statements that are present in all the candidate lists are shown. For example,

Database performance and query optimization 173


you could specify options Top 'n' most frequently run statements and Statements the following user
has ever run. The display shows those most frequently run statements in the cache that have been run
by the specified user. It does not show the most frequently run statements by the user (unless those
statements are also the most frequently run statements in the entire cache).

SQL Plan Cache column descriptions


Displays the columns that are used in the SQL Plan Cache Statements window.

Table 48. Columns used in SQL Plan Cache Statements window


Column name Description
Last Time Run Displays the last time that this statement was run.
Most Expensive Time (sec) The time taken for the longest run of this statement.
Total Processing Time (sec) The sum total time that all runs of this statement took to
process in seconds.
Total Times Run The total number of times that this statement ran.
Average Processing Time (sec) The average time per run that this statement took to process
in seconds.
Statement The statement text.
Plan Creation User Name The name of the user id that created the plan.
Job Name The name of the job that created the plan.
Job User The name of the user id that owned the job that created the
plan.
Job Number The job number of the job that created the plan.
Adjusted Average Processing Time (sec) The average time per run that this statement took to process
in seconds where anomalous runs are removed from the
average calculation. This time provides a realistic average
for a statement by ignoring a single (or few) run that was
atypical to the normal condition of the statement.
Average Result Set Rows The average number of result set rows that are returned
when this statement is run.
Average Temp Storage Used (MB) The average amount of temporary storage used when this
statement is run.
Plan Score The rating of this plan relative to other plans in the cache.
A plan with a higher rating relative to other plans remains in
the cache for a longer time. A plan with a lower rating relative
to other plans is removed from the cache sooner than the
other plans.
Plan Identifier A unique numeric identifier of the plan.
Total Cached Results Used The number of times a result set from a prior run of the
statement was reused on a subsequent run of the statement.
Optimization Time (sec) The amount of time that it took to optimize this statement.
System Name The system name.
Relational Database name Relational database name

174 IBM i: Performance and Query Optimization


SQL plan cache properties
The Plan Cache tab of the SQL Performance Center in IBM i Access Client Solutions (ACS) shows high-
level information about the SQL plan cache and overall query activity. This information includes cache
size, number of plans, number of full opens and pseudo-opens that have occurred.
This information can be used to view overall database activity. If tracked over time, it provides trends to
help you better understand the database utilization peaks and valleys throughout the day and week.
Several Plan Cache Properties can be changed by right-clicking a property and selecting Edit Value.
The following terms are used in regards to plan cache properties:
• Active Queries – queries that are currently open or in pseudo close mode.
• Full Open – describes a query run that requires a cursor to be built before the query executes and return
rows. A query that reuses a cursor is called a Pseudo Open.
• Unique Queries – unique SQL query statements. For the plan cache, this is uniqueness once tables are
resolved to their schemas.
• Hit Ratio – the percentage of time that the query optimizer, when searching the plan cache for a plan,
finds an existing plan for the query.
• Target Hit Ratio – the hit ratio percentage that the database tries to achieve by adjusting the plan
cache’s size. A larger size means plans stay in the cache longer and are therefore more likely to be found
and used for future runs of the query.
• Job Scoped – queries that reference tables or indexes that reside in the job’s QTEMP library. This
includes, for example, global temporary tables. By definition these job scoped plans and runtime
objects cannot be reused across jobs.
• Temporary Runtime Objects – the actual runtime executable objects used to process a query. These
include the execution tree (ROQ), hash tables, sorted lists, lists, and buffers. A certain number of these
objects are cached with the query plan in the cache so they can be reused.
• Longest Runs - information kept about the longest running instances of a query.
• Activity Thresholds – highest or largest values that are tracked by the database.
• …Since Start – the amount of activity since the cache was created (IPL).
Plan Cache Properties are divided into three main types:
• Summary and Usage – Information about plan usage, query usage and current conditions for the plan
cache and queries.
• Configuration – properties that can be adjusted by the user.
• Activity Threshold – tracked ‘high water mark’ of several key indicators.
To view the Plan Cache properties, select the SQL Performance Center from the main ACS window or from
the Tools menu of any ACS window.

Database performance and query optimization 175


The first tab in the SQL Performance Center window that appears will display all of the Plan Cache
properties. Changes to configurable properties may be made by clicking the Change Configuration...
button.

176 IBM i: Performance and Query Optimization


Table 49. Plan Cache Properties
Plan Cache Property Description
Time Of Summary Timestamp of when the properties were collected.
Plan Cache Creation Time Timestamp of when the plan cache was created
(IPL)

Active Query Summary


Number of Currently Active Queries Number of queries that are currently open or in
pseudo close mode.
Number of Queries Run Since Start Shows the total number of SQL queries run since
IPL
Note: This value includes job scoped queries.

Number of Query Full Opens Since Start Number of queries run since IPL that required a
cursor to be built before the query executed and
returned rows.

Database performance and query optimization 177


Table 49. Plan Cache Properties (continued)
Plan Cache Property Description

Plan Usage Summary


Current Number of Plans in Cache Current total number of plans in the plan cache
Total Number of Plans Built Since Start Number of plans built since IPL. This includes the
plans that have been pruned from the plan cache.
Total Number of SMP Plans Built Since Start The number of plans built since IPL that run with
SMP parallel processing.
Total Number of Unique Queries Since Start This value reflects the total number of unique
statements (SQL queries) run since IPL Note: This
value includes unique job scoped queries
Current Plan Cache Size Current size in MB of the plan cache. This does
not include the size of cached temporary runtime
objects.
Current Plan Cache Size Threshold The current maximum allowed size of the plan
cache.
This property is configurable.
• *AUTO indicates that the database manager will
manage the maximum size of the plan cache.
• A user specified value between 50 and 51200.
Size is specified in MB.

Maximum Plan Cache Size For AutoSizing If AutoSizing is active, the maximum plan cache
size.
This property is configurable if the Current® Plan
Cache Size Threshold is *AUTO.
• *DEFAULT(nn) - The database manager
determines, at IPL, the maximum size that the
plan cache can grow to under autosizing. Only
applicable if Size Threshold is set to *AUTO.
The database determined size is shown in
parentheses.
• nn – A user specified size between 50 and
51200. Size is specified in MB. While supported,
it should rarely be changed from *DEFAULT.
• *DISABLED - Indicates that plan cache auto
sizing has been disabled.

Current Plan Cache Hit Ratio The percentage of time the query optimizer found a
matching plan in the plan cache.
This value indicates the efficiency of the plan
cache. The higher the percentage the better.

178 IBM i: Performance and Query Optimization


Table 49. Plan Cache Properties (continued)
Plan Cache Property Description
Target Plan Cache AutoSize Hit Ratio This is the target hit ratio percentage that the
database manager tries to meet by adjusting the
plan cache size.
This property is configurable if the Current Plan
Cache Size Threshold is *AUTO.
• DEFAULT(nn) – The database manager sets the
target hit ratio. The database determined ratio is
shown in parentheses.
• nn – percentage from 1 to 99. While supported, it
should rarely be changed from *DEFAULT.
• *DISABLED - Indicates that plan cache auto
sizing has been disabled.

Total Number of Plan Cache Autosizing If autosizing is active, the number of times the plan
Adjustments cache autosized. This includes both plan cache
increase and decrease.
Last Plan Cache AutoSizing Adjustment If autosizing is active, the timestamp when the
plan cache was last autosized.
Last Autosizing Limited Due to Temporary Storage If autosizing is active, the timestamp of when
the plan cache last attempted to increase the
size of the plan cache but was unable to do so
because the temporary storage used on the system
exceeded limits.
Current Number of Job Scoped (QTEMP) Plans Current number of plans in the plan cache that
for queries that reference tables or indexes that
reside in the job’s QTEMP library. This includes,
for example, global temporary tables. By definition
these job scoped plans and runtime objects cannot
be reused across jobs.
Total Number of Job Scoped (QTEMP) Plans Built Total number of plans built for queries that
Since Start reference tables or indexes that reside in the job’s
QTEMP library.
Total Number of Unique Queries With Job Scoped This value reflects the total number of unique
(QTEMP) References Since Start statements (SQL queries) referencing temporary
files that have been run since IPL.
Total Times Plans Used from Cache Total number of plans that were reused from
the plan cache. (i.e. Plans that did not require a
reoptimization).

Database performance and query optimization 179


Table 49. Plan Cache Properties (continued)
Plan Cache Property Description
Total Plans Removed Number of plans removed from the plan cache
during optimization. Reasons that a plan may be
removed during optimization include the following,
but not limited to:
• plan no longer valid due to table and index
changes
• plan out of date due to changes in the number of
rows in the table
• more than 3 plans for the query exist in the plan
cache
• internal changes due to PTF applies or other
system level changes

Total Plans Pruned Total number of plans the plan cache pruner task
removed.
Number of Times Plan Cache Pruned Number of times that the plan cache pruner task
ran and removed plans from the plan cache.
Time Plan Cache was Last Pruned The timestamp of when the plan cache pruner task
last ran.
Current Number of Temporary Runtime Objects Current Number of Temporary Runtime Objects
Stored in Cache Stored in Cache
Current Total Size of Temporary Runtime Objects Current Total Size of Temporary Runtime Objects
stored in Cache stored in Cache
Maximum Number of Temporary Runtime Objects Maximum number of Temporary Runtime Objects
Stored Per Plan stored per plan.
This property is configurable.
• *DEFAULT(nn) - database determines the
maximum number of runtime objects (ROQs) to
keep per plan. The database determined number
is shown in parentheses.
• nn – A user specified value between 1 and
50 that is the maximum number of runtime
objects to keep per plan. A runtime ‘object’ is
all the runtime constructs (except the cursor)
used to execute the query. It includes the
ROQ, hash tables, sorts, etc… The database will
automatically clear big hash tables and sorts of
data contents (leaving only their shell) before
storing them with the plan. However, smaller
hashes and sorts will retain their contents.
Setting this value smaller will lessen the
temporary storage usage on the machine. Setting
this value higher can improve performance by
having more runtime objects ready to go during
full opens rather than having to build them.

Total Number of Temporary Indexes Created Total number of SQE created temporary indexes
(MTIs) since IPL.

180 IBM i: Performance and Query Optimization


Table 49. Plan Cache Properties (continued)
Plan Cache Property Description
Current Number of Temporary Indexes Current number of SQE created temporary indexes
(MTIs) on the system.
Current Total Size of Temporary Indexes The total size of all SQE created temporary indexes
(MTIs) currently on the system.
Number of Plans Rebuilt due to AQP Number of plans rebuilt to AQP.
Number of Query Mapping Errors Since Start This is the number of SQE query mapping errors
that have occurred since the last IPL. While a
number of mapping errors greater than 0 does
not indicate a problem, a significant number of
mapping errors can negatively affect performance
and may require further investigation.
Maximum Number of Longest Runs Allowed Per The Maximum Number of Longest Runs Allowed
Plan Per Plan determines how many longest runs are
maintained per plan.
This property is configurable.
• *DEFAULT(nn) - The database manager
determines the maximum number of longest
run entries to keep per plan. The database
determined number is shown in parentheses.
• nn – A user specified value between 1 and 50
indicating the maximum number of longest runs
information to keep per plan
Note: These can be seen by bringing up a show
statements of the live cache, right clicking, and
selecting Longest Runs

Plan Cache Activity Thresholds


The Activity Thresholds group of properties track
the upper thresholds of activity for both plans and
query activity. The values represent the maximum
values achieved since the Threshold Start Time.
Each threshold shows both the maximum value
and the timestamp of when that maximum was
reached.

Activity Thresholds Start Time The time from which the tracking started. This
value can be reset (to zero) to reset all the
thresholds and restart tracking.
Note: All thresholds are reset at one time,
thresholds cannot be reset individually. Start Time
restarts each IPL.

Highest Number of Active Queries at One Time The highest number of open plus pseudo closed
cursors (queries) at a given point in time
Highest Number of Plans in Cache The largest number of plans in the plan cache at a
given point in time

Database performance and query optimization 181


Table 49. Plan Cache Properties (continued)
Plan Cache Property Description
Highest Number of Temporary Runtime Objects The highest number of inactive runtime executable
Stored in Cache objects stored (cached) away (for future reuse) in
the plan cache at a given point in time
Largest Total Size of Temporary Runtime Objects The largest amount of temporary storage, in MB,
Stored in Cache consumed by the inactive runtime executable
objects stored (cached) away in the plan cache at a
given point in time

Query Supervisor
The Query Supervisor group of properties provide
historical information about the interaction of the
Query Supervisor with queries running on the
system.

Number of thresholds reached The number of Query Supervisor thresholds that


have been reached since IPL.
Most recent job to reach a threshold The name and timestamp of the most recent job to
reach a Query Supervisor threshold.
Number of queries terminated The number of queries that have been terminated
since IPL at the request of a Query Supervisor exit
program.
Most recent job to have a query terminated The name and timestamp of the most recent job to
have a query terminated at the request of a Query
Supervisor exit program.
Most recent exit point program failure The name and timestamp of the most recent job to
encounter an error when using a Query Supervisor
exit program.

Creating SQL plan cache snapshots


The New > Snapshot option allows for the creation of a snapshot from the plan cache.
Unlike the snapshot option under Show Statements, it allows you to create a snapshot without having to
first view the queries.

182 IBM i: Performance and Query Optimization


The same filtering options are provided here as on the Show Statements screen.
The stored procedure, qsys2.dump_plan_cache, provides the simplest, programmatic way to create a
database monitor file output (snapshot) from the plan cache. The dump_plan_cache procedure takes two
parameters, library name and file name, for identifying the resulting database monitor file. If the file does

Database performance and query optimization 183


not exist, it is created. For example, to dump the plan cache to a database performance monitor file in
library QGPL:

CALL qsys2.dump_plan_cache('QGPL','SNAPSHOT1');

SQL plan cache event monitor


The SQL plan cache event monitor records changes in your plan cache.
You can access the SQL plan cache event monitor through the System i Navigator interface or by calling
the procedures directly.
The SQL plan cache event monitor captures monitor records of plans as they are removed from the plan
cache. The event monitor is useful for ensuring that all performance information potentially available in
the cache is captured even if plans are removed from the cache. Combining the event monitor output with
a plan cache snapshot provides a composite view of the cache from when the event monitor was started
until the snapshot is taken.
The event monitor allows the same filtering options as described for Show statements and
NewSnapshot. The exceptions are that the Top 'n' most frequently run statements and the Top 'n'
statements with largest total accumulated runtime are not shown. Once a statement is removed from
the cache, it is no longer compared to other plans. Therefore, these two 'Top n' filters do not make sense
for pruned plans.

Accessing the SQL plan cache with SQL stored procedures


The System i Navigator provides a visual interface into the plan cache. However, the plan cache is also
accessible through stored procedures which can be called using the SQL CALL statement.
See “Plan Cache Services” on page 355 for the descriptions of these procedures.

CLEAR_PLAN_CACHE
The CLEAR_PLAN_CACHE procedure is a plan cache clearing alternative to performing a system IPL.

CLEAR_PLAN_CACHE procedure
>>-CLEAR_PLAN_CACHE --()----------------------------------><

The schema is QSYS2.


This procedure is used primarily in performance test and QA environments. It provides database
performance analysts with a way to create a consistent environment from which to evaluate potential
database performance changes. The procedure will clear all plans in the system SQL Plan Cache that
exist at the time the procedure is run. Besides clearing the plan information, any Maintained Temporary
Indexes (MTIs) not currently in use by a query will be deleted as part of the clear. SQL queries run while
the CLEAR_PLAN_CACHE procedure is running may have their plans removed, but the queries themselves
will not incur a failure related to plan removal. Any SQL queries run after the clear is complete will begin
to repopulate the plan cache.
The time the CLEAR_PLAN_CACHE procedure takes to run will vary depending on the plan cache size. To
avoid tying up an interactive job, it is recommended to submit the procedure in a background job using a
combination of the Submit Job (SBMJOB) and Run SQL (RUNSQL) CL commands.
Authorization: The CLEAR_PLAN_CACHE procedure requires that the authorization ID associated with
the statement has *JOBCTL special authority or QIBM_DB_SQLADM function usage.
Errors: The procedure will fail with SQL0443 and SQL0552 if the caller does not have the required
authority.
Example:

184 IBM i: Performance and Query Optimization


SBMJOB CMD(RUNSQL SQL('CALL QSYS2.CLEAR_PLAN_CACHE()') COMMIT(*NONE) NAMING(*SQL))

Verifying the performance of SQL applications


You can verify the performance of an SQL application by using commands.
The commands that can help you verify performance:

Display Job You can use the Display Job (DSPJOB) command with the OPTION(*OPNF)
(DSPJOB) parameter to show the indexes and tables used by an application running in a job.
You can also use DSPJOB with the OPTION(*JOBLCK) parameter to analyze object
and row lock contention. It displays the objects and rows that are locked and the
name of the job holding the lock.
Specify the OPTION(*CMTCTL) parameter on the DSPJOB command to show the
isolation level, the number of rows locked during a transaction, and the pending
DDL functions. The isolation level displayed is the default isolation level. The actual
isolation level, used for any SQL program, is specified on the COMMIT parameter of
the CRTSQLxxx command.

Print SQL The Print SQL Information (PRTSQLINF) command lets you print
Information information about the embedded SQL statements in a program, SQL package, or
(PRTSQLINF) service program. The information includes the SQL statements, access plans used,
and the command parameters used to precompile the source member.
Start Database You can use the Start Database Monitor (STRDBMON) command to capture
Monitor to a file information about every SQL statement that runs.
(STRDBMON)
Change Query You can use the Change Query Attribute (CHGQRYA) command to change
Attribute the query attributes for the query optimizer. Among the attributes that can be
(CHGQRYA) changed by this command are the predictive query governor, parallelism, and the
query options.
Start Debug You can use the Start Debug (STRDBG) command to put a job into debug
(STRDBG) mode, and optionally add as many as 20 programs, 20 class files, and 20 service
programs to debug mode. It also specifies certain attributes of the debugging
session. For example, it can specify whether database files in production libraries
can be updated while in debug mode.
Related information
Display Job (DSPJOB) command
Print SQL Information (PRTSQLINF) command
Start Database Monitor (STRDBMON) command
Change Query Attributes (CHGQRYA) command
Start Debug (STRDBG) command

Examining query optimizer debug messages in the job log


Query optimizer debug messages issue informational messages to the job log about the implementation
of a query. These messages explain what happened during the query optimization process.
For example, you can learn:
• Why an index was or was not used
• Why a temporary result was required
• Whether joins and blocking are used
• What type of index was advised by the optimizer
• Status of the job queries

Database performance and query optimization 185


• Indexes used
• Status of the cursor
The optimizer automatically logs messages for all queries it optimizes, including SQL, call level interface,
ODBC, OPNQRYF, and SQL Query Manager.

Viewing debug messages using STRDBG command:


STRDBG command puts a job into debug mode. It also specifies certain attributes of the debugging
session. For example, it can specify whether database files in production schemas can be updated while
in debug mode. For example, use the following command:

STRDBG PGM(Schema/program) UPDPROD(*YES)

STRDBG places in the job log information about all SQL statements that run.

Viewing debug messages using QAQQINI table:


You can also set the QRYOPTLIB parameter on the Change Query Attributes (CHGQRYA) command
to a user schema where the QAQQINI table exists. Set the parameter on the QAQQINI table to
MESSAGES_DEBUG, and set the value to *YES. This option places query optimization information in
the job log. Changes made to the QAQQINI table are effective immediately and affect all users and
queries that use this table. Once you change the MESSAGES_DEBUG parameter, all queries that use this
QAQQINI table write debug messages to their respective job logs. Pressing F10 from the command Entry
panel displays the message text. To see the second-level text, press F1 (Help). The second-level text
sometimes offers hints for improving query performance.

Viewing debug messages in Run SQL Scripts:


To view debug messages in Run SQL Scripts, from the Options menu, select Include Debug Messages in
Job Log. Then from the View menu, select Job Log. To view detailed messages, double-click a message.

Viewing debug messages in Visual Explain:


In Visual Explain, debug messages are always available. You do not need to turn them on or off. Debug
messages appear in the lower portion of the window. You can view detailed messages by double-clicking
a message.

Print SQL Information


The Print SQL Information (PRTSQLINF) command returns information about the embedded SQL
statements in a program, SQL package (used to store the access plan for a remote query), or service
program. This information is then stored in a spooled file.
PRTSQLINF provides information about:
• The SQL statements being executed
• The type of access plan used during execution. How the query is implemented, indexes used, join order,
whether a sort is used, whether a database scan is used, and whether an index is created.
• A list of the command parameters used to precompile the source member for the object.
• The CREATE PROCEDURE and CREATE FUNCTION statement text used to create external procedures or
User Defined Functions.
This output is like the information that you can get from debug messages. However, while query debug
messages work at runtime, PRTSQLINF works retroactively. You can also see this information in the
second-level text of the query governor inquiry message CPA4259.
You can issue PRTSQLINF in a couple of ways. First, you can run the PRTSQLINF command against a
saved access plan. You must execute or at least prepare the query (using the SQL PREPARE statement)

186 IBM i: Performance and Query Optimization


before you use the command. It is best to execute the query because the index created as a result of
PREPARE is relatively sparse. It could well change after the first run. PRTSQLINF's requirement of a saved
access plan means that the command cannot be used with OPNQRYF.
You can also run PRTSQLINF against functions, stored procedures, triggers, SQL packages, and programs
from System i Navigator. This function is called Explain SQL. To view PRTSQLINF information, right-click
an object and select Explain SQL.
Related information
Print SQL Information (PRTSQLINF) command

Query optimization tools: Comparison


Use this table to find the information each tool can provide, when it analyzes your queries, and the tasks it
can do to improve your queries.

Table 50. Optimization tool comparison


PRTSQLINF STRDBG or CHGQRYA File-based monitor Memory-Based Visual Explain
(STRDBMON) Monitor
Available without Only available when Only available when Only available when Only available when
running query (after the query is run the query is run the query is run the query is
access plan has explained
been created)
Displayed for all Displayed only for Displayed only for Displayed only for Displayed only for
queries in SQL those queries which those queries which those queries which those queries that
program, whether are executed are executed are executed are explained
executed or not
Information about Limited information All information All information All information
host variable about the about host variables, about host variables, about host variables,
implementation implementation of implementation, and implementation, and implementation, and
host variables values values values
Available only to Available to all query Available to all query Available only to Available through
SQL users with users (OPNQRYF, users (OPNQRYF, SQL interfaces System i Navigator
programs, packages, SQL, QUERY/400) SQL, QUERY/400) Database and API
or service programs interface
Messages are Messages are Performance rows Performance Information is
printed to spool file displayed in job log are written to information is displayed visually
database table collected in memory through System i
and then written to Navigator
database table
Easier to tie Difficult to tie Uniquely identifies Repeated query Easy to view
messages to query messages to query every query, requests are implementation
with subqueries or with subqueries or subquery, and summarized of the query
unions unions materialized view and associated
information

SQL Error Logging Facility (SELF)


The SQL Error Logging Facility (SELF) provides a mechanism that can be used to understand when SQL
statements are encountering specific SQL errors or warnings. SELF is built into Db2 for i and can be
enabled in specific jobs or system wide.
SELF differs from the Db2 for i SQL Performance Monitoring or Database Monitoring feature in some
significant ways:

Database performance and query optimization 187


1. SELF is configured by the client to identify specific SQLCODE values that Db2 for i should use for SELF
processing when a user-initiated SQL statement completes with a matching SQLCODE value.
2. SELF collects point-of-failure information which is accessible through the QSYS2.SQL_ERROR_LOG
view.
3. SELF runs when an SQL statement completes with an SQLCODE value that matches a list of values in
the SYSIBMADM.SELFCODES built-in global variable.
4. SELF is safe to use in production environments. It has no performance impact to SQL statements
that complete successfully or for any SQL errors or warnings where the SQLCODE does not match the
values listed in the SYSIBMADM.SELFCODES global variable.
By registering the SQLCODE values you are interested in monitoring at either a job or system level, each
time one of the SQLCODE values is returned, an entry will be logged in the SELF table. For each SQLCODE,
information such as the program name, call stack, and SQL statement text are recorded. This information
is collected while the application is running. Logging only happens during SQL error processing, so it has
no performance impact on SQL statements that complete successfully. Errors that are issued during a
precompile of an embedded SQL program are not recorded. The QSYS2.SQL_ERROR_LOG view can be
used to examine the information that has been collected. See “SQL_ERROR_LOG view” on page 331 for
the definition of the view.

Registering SQLCODEs with SELF


Users configure the SQLCODEs that should be processed by SELF through the SYSIBMADM.SELFCODES
global variable. By default, this global variable is set to NULL for all jobs, which means that SELF is turned
off and will not log anything. To enable SELF, the global variable needs to be set, providing one or more
SQLCODE values. See “SELFCODES global variable” on page 331 for more information.
The setting of the SELFCODES global variable applies to the SQL session where it is set. An SQL session is
equivalent to an activation group. If SELFCODES has a default value, that value applies to all sessions in
all user jobs. Changing the default value for the SELFCODES global variable does not affect active jobs. If,
however, the user wants to enable SELF only in specific jobs, the SELFCODES global variable value can be
changed in those jobs.
A string of SQLCODE values assigned to the SELFCODES global variable must conform to the following
rules:
• An error SQLCODE must be preceded by a single minus sign ('-').
• A warning SQLCODE can be preceded by an optional plus sign ('+').
• Multiple SQLCODE values in the string can be separated by any number of blanks and commas between
values.
• Up to 32 SQLCODE values can be provided in the string. If more than 32 are specified, only the first 32
are used by SELF. No error is issued.
• If a special value exists in the string, it must be the only entry in the string:
– The special value of *ERROR specifies all SQLCODEs that are error conditions (negative values).
– The special value of *WARN specifies all SQLCODEs that are warning conditions (positive values).
– The special value of *ALL specifies all SQLCODEs that are error or warning conditions.
– The special value of *NONE turns off SELF processing.
• A string containing the value 0 turns off SELF processing, even if other SQLCODE values are found in the
SELFCODES string.
• A value of 100 or +100 is not allowed.
• There is no verification that a specified SQLCODE is used by Db2 for i.
• Any character other than a digit (0-9), minus, plus, blank, or comma is not valid and will remove all
SQLCODEs from logging. Using the SYSIBMADM.VALIDATE_SELF scalar function to perform validation of
a string to be used for SELFCODES is recommended. See “VALIDATE_SELF scalar function” on page 334
for a description of this function.

188 IBM i: Performance and Query Optimization


Setting SELFCODES within a specific job
To enable SELF only within a specific job, the SELFCODES global variable must be changed within that job.
For example, to set the list of SQLCODEs within a job, use the SQL SET statement. This has no effect on
other jobs. Invoke the VALIDATE_SELF function to verify the string is properly formed.

SET SYSIBMADM.SELFCODES = SYSIBMADM.VALIDATE_SELF('-514, -204, -501, +30, -199');

Each time the SELFCODES global variable is set, the new list of SQLCODE values replaces any SQLCODEs
that were previously being used.
Setting SELFCODES for all user jobs
When a job first uses SQL, its value for the SELFCODES global variable is assigned using the default value
specified for the SELFCODES global variable. When the default is changed, it will apply to jobs that start
after the change is made.
To change the default for the SELFCODES global variable, use the CREATE OR REPLACE VARIABLE SQL
statement. Note that the data type of the global variable must remain VARCHAR(256).

CREATE OR REPLACE VARIABLE SYSIBMADM.SELFCODES VARCHAR(256)


DEFAULT '-514, -204, -501, +30, -199';

SELF data repository


When an SQL statement completes execution, SELF will determine whether the SQLCODE value matches
the list of SQLCODE values specified within the SELFCODES global variable. If the SQLCODE is in the list
that is being recorded for the session, information about the failure and the environment is collected and
written to the QSYS2.SQL_ERRORT table.
QSYS2.SQL_ERRORT - This is the master repository for SELF detail. SELF inserts or updates rows in this
table as SQL statements complete with an SQLCODE that matches a value specified within SELFCODES.
By default, *PUBLIC is set to *EXCLUDE for SQL_ERRORT.
QSYS2.SQL_ERROR_LOG - This view is the preferred interface for accessing SELF detail. To access the
data within SQL_ERROR_LOG, the caller must have *ALLOBJ special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.
There are five details that determine whether SELF will insert a new row or update an existing row in
SQL_ERRORT:
1. Application library name
2. Application program name
3. Application module name
4. SQLCODE
5. SQL statement text
If these key values are the same as a row that has already been logged, the existing row is updated
with information about the new occurrence of the error. The number of times the specific error has been
encountered is incremented. Otherwise, a new row is inserted into SQL_ERRORT.
If any errors occur while attempting to update SQL_ERRORT, information is not recorded.
If SQL_ERRORT does not exist, it will be recreated.

Viewing the SELF log


The QSYS2.SQL_ERROR_LOG view should be used to look at the entries that are recorded by SELF. This
view requires the user to be authorized to the QIBM_DB_SQLADM function usage ID or have *ALLOBJ
special authority.
To find all entries recorded for a specific application program, the following query can be used.

Database performance and query optimization 189


SELECT * FROM QSYS2.SQL_ERROR_LOG
WHERE PROGRAM_LIBRARY = 'PGMLIB' AND PROGRAM_NAME = 'PGM1'
ORDER BY LOGGED_TIME DESC;

To find all entries where the same error has occurred for the same statement in the same program, the
following query can be used.

SELECT * FROM QSYS2.SQL_ERROR_LOG


WHERE NUMBER_OCCURRENCES > 1
ORDER BY NUMBER_OCCURRENCES DESC;

Maintaining the SELF log


Similar to the Index Advisor table (QSYS2.SYSIXADV), the database only inserts or updates rows in the
SELF log file (QSYS2.SQL_ERRORT). Rows are never deleted.
The user of SELF must decide when and if rows within SQL_ERRORT should be deleted. For example,
maybe SELF was being used to review and evaluate SQL application failures before releasing a new
version of an application. After an initial set of problems are understood and resolved, the application
team could ask for SQL_ERRORT to be cleared of historical SELF detail before another iteration of testing
occurs.
To remove rows from the table haven’t had a new occurrence logged in the last 30 days:

DELETE FROM QSYS2.SQL_ERRORT


WHERE DATE(LOGGED_TIME) < CURRENT DATE - 30 DAYS;

SELF example
This example shows how SELF can be used to capture point-of-failure detail for SQL statements that are
failing because they cannot acquire the necessary locks and for SQL statements that are failing due to
lack of authority. The SQLCODEs the example will capture details for are:
• SQLCODE -913 : Row or object &1 in &2 type *&3 in use.
• SQLCODE +551 : Not authorized to object &1 in &2 type *&3.
• SQLCODE -551 : Not authorized to object &1 in &2 type *&3.
• SQLCODE +552 : Not authorized to &1.
• SQLCODE -552 : Not authorized to &1.
Step 1. Build a SELF control string
Use the VALIDATE_SELF scalar function to confirm that the SELF control string is well-formed.

VALUES SYSIBMADM.VALIDATE_SELF('-913, -551, -552, +551,+552');

Figure 1. Result string from VALIDATE_SELF

Step 2. Set up SELF at the system level


To enable SELF to work across all future user jobs, the SYSIBMADM.SELFCODES global variable needs to
be recreated using a DEFAULT string set to the SQLCODE values to log. The string that was returned from
step 1 is used, since we know it is a valid string.

CREATE OR REPLACE VARIABLE SYSIBMADM.SELFCODES VARCHAR(256)


DEFAULT '551, 552, -551, -552, -913';

190 IBM i: Performance and Query Optimization


Step 3. Monitor results recorded by SELF
After letting SELF run for a user-determined period of time, check the SELF log.
Notice how the SELF log includes deep details on who, what, and when the failure occurred. There’s even
detail regarding the values of the client special registers at the point of failure.
When a failure occurs multiple times, SELF shows not only the total occurrence count, but also detail
about both the first and most recent failure occurrence.
To examine the errors that were set to be captured, run the following query:

SELECT *
FROM QSYS2.SQL_ERROR_LOG
WHERE LOGGED_SQLCODE IN (551, 552, -551, -552, -913)
ORDER BY LOGGED_TIME DESC;

Figure 2. SQL_ERROR_LOG result, part 1

Figure 3. SQL_ERROR_LOG result, part 2

Figure 4. SQL_ERROR_LOG result, part 3

Figure 5. SQL_ERROR_LOG result, part 4

The following query can be used to examine the stack at the point of failure for every -551 authorization
failure for a DELETE statement.

WITH SELF_ROWS AS (SELECT ROW_NUMBER() OVER() AS INSTANCE, LOG.* FROM QSYS2.SQL_ERROR_LOG LOG
WHERE LOGGED_SQLCODE = -551 AND
STATEMENT_OPERATION = 'DL')

SELECT INSTANCE, STATEMENT_TEXT, A.*


FROM SELF_ROWS,
JSON_TABLE(INITIAL_STACK, 'lax $.initial_stack[*]'
COLUMNS(

Database performance and query optimization 191


ORDINAL_POSITION INTEGER PATH 'lax $."ORD"',
PROGRAM_TYPE VARCHAR(10) CCSID 1208 PATH 'lax $."TYPE"',
PROGRAM_LIB VARCHAR(10) CCSID 1208 PATH 'lax $."LIB"',
PROGRAM_NAME VARCHAR(10) CCSID 1208 PATH 'lax $."PGM"',
MODULE_NAME VARCHAR(10) CCSID 1208 PATH 'lax $."MODULE"',
PROCEDURE_NAME VARCHAR(128) CCSID 1208 PATH 'lax $."PROC"',
STATEMENT_NUMBER VARCHAR(10) CCSID 1208 PATH 'lax $."STMT"',
ACTIVATION_GROUP VARCHAR(10) CCSID 1208 PATH 'lax $."ACTGRP"'
)
) A
ORDER BY INSTANCE, A.ORDINAL_POSITION;

Figure 6. Stack for SELF log

Changing the attributes of your queries


You can modify different types of query attributes for a job with the Change Query Attributes
(CHGQRYA) CL command. You can also use the System i Navigator Change Query Attributes interface.
Related concepts
Plan cache
The plan cache is a repository that contains the access plans for queries that were optimized by SQE.
Objects processed in parallel
The Db2 Symmetric multiprocessing feature provides the optimizer with additional methods for retrieving
data that include parallel processing. Symmetrical multiprocessing is a form of parallelism achieved on
a single system where multiple CPU and I/O processors sharing memory and disk work simultaneously
toward a single result.
Related information
Change Query Attributes (CHGQRYA) command

Controlling queries dynamically with the query options file QAQQINI


The query options file QAQQINI support provides the ability to dynamically modify or override the
environment in which queries are executed. This modification is done through the Change Query
Attributes (CHGQRYA) command and the QAQQINI file. The query options file QAQQINI is used to set
some attributes used by the database manager.
For each query that is run the query option values are retrieved from the QAQQINI file in the schema
specified on the QRYOPTLIB parameter of the CHGQRYA CL command and used to optimize or implement
the query.
Environmental attributes that you can modify through the QAQQINI file include:
• ACTIVE_JOBS
• ALLOW_ADAPTIVE_QUERY_PROCESSING
• ALLOW_ARRAY_VALUE_CHANGES
• ALLOW_DDL_CHANGES_WHILE_OPEN
• ALLOW_EVI_ONLY_ACCESS
• ALLOW_TEMPORARY_INDEXES
• APPLY_REMOTE
• ASYNC_JOB_USAGE

192 IBM i: Performance and Query Optimization


• CACHE_RESULTS
• COLLATE_ERRORS
• COMMITMENT_CONTROL_LOCK_LIMIT
• CONCURRENT_ACCESS_BEHAVIOR
• DETERMINISTIC_UDF_SCOPE
• FIELDPROC_ENCODED_COMPARISON
• FORCE_JOIN_ORDER
• IGNORE_LIKE_REDUNDANT_SHIFTS
• KEY_RANGE_ESTIMATE_TIMEOUT
• LIMIT_PREDICATE_ OPTIMIZATION
• LOB_LOCATOR_THRESHOLD
• MATERIALIZED_QUERY_TABLE_REFRESH_AGE
• MATERIALIZED_QUERY_TABLE _USAGE
• MEMORY_POOL_PREFERENCE
• MESSAGES_DEBUG
• NORMALIZE_DATA
• OPEN_CURSOR_CLOSE_COUNT
• OPEN_CURSOR_THRESHOLD
• OPTIMIZATION_GOAL
• OPTIMIZE_STATISTIC_LIMITATION
• PARALLEL_DEGREE
• PARAMETER_MARKER_CONVERSION
• PSEUDO_OPEN_CHECK_HOST_VARS
• QUERY_TIME_LIMIT
• REOPTIMIZE_ACCESS_PLAN
• SQE_NATIVE_ACCESS_POSITION_BEHAVIOR
• SQLSTANDARDS_MIXED_CONSTANT
• SQL_CONCURRENT_ACCESS_RESOLUTION
• SQL_DECFLOAT_WARNINGS
• SQL_FAST_DELETE_ROW_COUNT
• SQL_GVAR_BUILD_RULE
• SQL_MODIFIES_SQL_DATA
• SQL_PSEUDO_CLOSE
• SQL_STMT_COMPRESS_MAX
• SQL_STMT_REUSE
• SQL_SUPPRESS_MASKED_DATA_DETECTION
• SQL_SUPPRESS_WARNINGS
• SQL_TRANSLATE_ASCII_TO_JOB
• SQL_XML_DATA_CCSID
• STAR_JOIN
• STORAGE_LIMIT
• SYSTEM_SQL_STATEMENT_CACHE
• SYSTIME_PERIOD_ADJ

Database performance and query optimization 193


• TEXT_SEARCH_DEFAULT_TIMEZONE
• UDF_TIME_OUT
• VARIABLE_LENGTH_OPTIMIZATION

Specifying the QAQQINI file with CHGQRYA


Use the Change Query Attributes (CHGQRYA) command with the QRYOPTLIB (query options
library) parameter to specify which schema currently contains or contains the query options file QAQQINI.
The query options file is retrieved from the schema specified on the QRYOPTLIB parameter for each
query. It remains in effect for the duration of the job or user session, or until the QRYOPTLIB parameter is
changed by the Change Query Attributes (CHGQRYA) command.
If the Change Query Attributes (CHGQRYA) command is not issued, or is issued without the
QRYOPTLIB parameter specified, QUSRSYS is searched for the QAQQINI file. If a query options file is
not found, no attributes are modified. Since the system ships without an INI file in QUSRSYS, you might
receive a message indicating that there is no INI file. This message is not an error but an indication that a
QAQQINI file that contains all default values is being used. The initial value of the QRYOPTLIB parameter
for a job is QUSRSYS.
Related information
Change Query Attributes (CHGQRYA) command

Creating the QAQQINI query options file


Each system is shipped with a QAQQINI template file in schema QSYS. The QAQQINI file in QSYS is to be
used as a template when creating all user specified QAQQINI files.
To create your own QAQQINI file, use the Create Duplicate Object (CRTDUPOBJ) command.
Create a copy of the QAQQINI file in the schema specified on the Change Query Attributes
(CHGQRYA) QRYOPTLIB parameter. The file name must remain QAQQINI. For example:

CRTDUPOBJ OBJ(QAQQINI)
FROMLIB(QSYS)
OBJTYPE(*FILE)
TOLIB(MYLIB)
DATA(*YES)
TRG(*YES)

System-supplied triggers are attached to the QAQQINI file in QSYS therefore it is imperative that the only
means of copying the QAQQINI file is through the CRTDUPOBJ CL command. If another means is used,
such as CPYF, then the triggers could be corrupted. An error is signaled that the options file cannot be
retrieved or that the options file cannot be updated.
Because of the trigger programs attached to the QAQQINI file, the following CPI321A informational
message is displayed six times in the job log when the CRTDUPOBJ CL is used to create the file. These
messages are not an error; they are only informational messages.
CPI321A Information Message: Trigger QSYS_TRIG_&1___QAQQINI___00000&N in library &1 was
added to file QAQQINI in library &1. The ampersand variables (&1, &N) are replacement variables that
contain either the library name or a numeric value.
Note: It is highly recommended that the file QAQQINI, in QSYS, not be modified. This file is the original
template that is duplicated into QUSRSYS or a user specified library for use.
Related information
Change Query Attributes (CHGQRYA) command
Create Duplicate Object (CRTDUPOBJ) command

QAQQINI file override support


If you find working with the QAQQINI query options file cumbersome, consider using the
QSYS2.OVERRIDE_QAQQINI procedure. Instead of creating, managing, and using a QAQQINI *FILE
object directly, this procedure can be called to work with a temporary version of the INI file. It uses

194 IBM i: Performance and Query Optimization


user-specified options and values. The support relies upon the QTEMP library, so any changes affect only
the job which calls the procedure.
See OVERRIDE_QAQQINI procedure for more information.

QAQQINI query options file format


The QAQQINI file is shipped in the schema QSYS. It has a predefined format and has been pre-populated
with the default values for the rows.
Query Options File:

A UNIQUE
A R QAQQINI TEXT('Query options + file')
A QQPARM 256A VARLEN(10) +
TEXT('Query+
option parameter') +
COLHDG('Parameter')
A QQVAL 256A VARLEN(10) +
TEXT('Query option +
parameter value') +
COLHDG('Parameter Value')
A QQTEXT 1000G VARLEN(100) +
TEXT('Query +
option text') +
ALWNULL +
COLHDG('Query Option' +
'Text') +
CCSID(13488) +
DFT(*NULL)
A K QQPARM

Setting the options within the query options file


The QAQQINI file query options can be modified with the INSERT, UPDATE, or DELETE SQL statements.
For the following examples, a QAQQINI file has already been created in library MyLib. To update an
existing row in MyLib/QAQQINI use the UPDATE SQL statement. This example sets MESSAGES_DEBUG =
*YES so that the query optimizer prints out the optimizer debug messages:

UPDATE MyLib/QAQQINI SET QQVAL='*YES'


WHERE QQPARM='MESSAGES_DEBUG'

To delete an existing row in MyLib/QAQQINI use the DELETE SQL statement. This example removes the
QUERY_TIME_LIMIT row from the QAQQINI file:

DELETE FROM MyLib/QAQQINI


WHERE QQPARM='QUERY_TIME_LIMIT'

To insert a new row into MyLib/QAQQINI use the INSERT SQL statement. This example adds the
QUERY_TIME_LIMIT row with a value of *NOMAX to the QAQQINI file:

INSERT INTO MyLib/QAQQINI


VALUES('QUERY_TIME_LIMIT','*NOMAX','New time limit set by DBAdmin')

QAQQINI query options file authority requirements


QAQQINI is shipped with a *PUBLIC *USE authority. This authority allows users to view the query options
file, but not change it. Changing the values of the QAQQINI file affects all queries run on the system. Allow
only the system or database administrator to have *CHANGE authority to the QAQQINI query options file.
The query options file, which resides in the library specified on the Change Query Attributes
(CHGQRYA) CL command QRYOPTLIB parameter, is always used by the query optimizer. It is used even
if the user has no authority to the query options library and file. This authority provides the system
administrator with an additional security mechanism.
When the QAQQINI file resides in the library QUSRSYS the query options affects all the query users
on the system. To prevent anyone from inserting, deleting, or updating the query options, the system

Database performance and query optimization 195


administrator must remove update authority from *PUBLIC to the file. This update authority prevents
users from changing the data in the file.
A copy of the QAQQINI file can also reside in a user library. If that library is specified on the QRYOPTLIB
parameter of the Change Query Attributes (CHGQRYA) command, the query options affect all the
queries run for that user job. To prevent the query options from being retrieved from a particular library
the system administrator can revoke authority to the Change Query Attributes (CHGQRYA) CL
command.

QAQQINI file system-supplied triggers


The query options file QAQQINI file uses a system-supplied trigger program in order to process any
changes made to the file. A trigger cannot be removed from or added to the file QAQQINI.
If an error occurs on the update of the QAQQINI file (an INSERT, DELETE, or UPDATE operation), the
following SQL0443 diagnostic message is issued:

Trigger program or external routine detected an error.

QAQQINI query options


There are different options available for parameters in the QAQQINI file.
The following table summarizes the query options that can be specified on the QAQQINI command:
Table 51. Query Options Specified on QAQQINI Command

Parameter Value Description

Average active jobs will be computed based on system


*DEFAULT
information. This is the recommended setting.

ACTIVE_JOBS The number of active jobs that will be used by the query
This option specifies what should be used for active jobs during optimizer to determine fair share. Specify a value between 1
optimization. The number of active jobs is used in determining the and 8192. Specifying a value other than default means that you
Integer value (1 ::
optimizer fair share of memory. may not get all of the performance benefits from the optimizer
8192)
determining a plan using the memory fair share based on actual
system usage. Usage of this setting is intended primarily for
debug or modeling query plans based on an optimizer fair share.

*DEFAULT The default value is set to *YES.

Allows Adaptive query processing to occur for this query.


The existing QAQQINI options that affect AQP are the following:

ALLOW_ADAPTIVE_QUERY_PROCESSING • If the REOPTIMIZE_ACCESS_PLAN QAQQINI option is set


to *ONLY_REQUIRED, AQP does not reoptimize the original
Specifies whether Adaptive Query Processing (AQP) processing is plan. *ONLY_REQUIRED indicates the user does not want the
done for a query. query reoptimized unless there is a functional reason to do
*YES
Adaptive query processing uses runtime statistics to look for poor so. *ONLY_REQUIRED takes precedence over AQP.
performing queries and potentially replace the poor plan with an • Join order requirements specified by the user in the
improved plan. FORCE_JOIN_ORDER QAQQINI option take precedence over
AQP. If the user specifies the primary table in the join order,
any AQP primary recommendations will be placed after the
primary table if they are different.

*NO Adaptive query processing cannot be used for this query.

196 IBM i: Performance and Query Optimization


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

*DEFAULT The default value is set to *NO.

Do not allow changes to values in arrays referenced in the query


to be visible after the query is opened.
All values which could be referenced in a query are copied
during query open processing. Any changes to values in arrays
after the query is opened are not visible.
Produces queries with predictable and reproducible results,
*NO but might have a performance penalty when working with
large arrays or large array elements. The penalty is less if all
the references to arrays are simple non-column values, for
example, :ARRAY[1] or :ARRAY[:hv2].
Use of column values from a table to index the ARRAY, or using
the UNNEST() function results in copies of the entire array being
made. These copies have the largest performance penalty.

Allow changes to values in arrays to be visible to the query while


the query is running. The arrays are not copied during the open
processing of the query. If the array values are changed during
the processing of queries, the results of the query might be
unpredictable.
Performance might be improved for queries which reference
ALLOW_ARRAY_VALUE_CHANGES large arrays in complex array index lookup operations, such
Specifies whether changes to the values of array elements are as :Array[column-name], or when using UNNEST. Large
visible to the query while the query is running. arrays include arrays that have thousands of elements, or
elements with a large size. Array index lookups using simple
index values, such as :ARRAY[1] or :ARRAY[:hv2], see
minimal performance improvements.
Performance of some queries might be negatively impacted.
For example, later queries that could reuse the results if they
were cached to avoid recalculation where the cached result is
*YES applicable.
Procedures that can run with *YES and still expect predictable
results have the following characteristics:
1. Contain no cursor declarations.
2. Receive arrays as input parameters:
• and do not contain SET statements which reference
arrays on the left side of the SET, and
• and have no SQL statements with INTO clauses
referencing arrays.
3. Do not contain SET statements which reference arrays on
the left side of the set:
• and have no SQL statements with INTO clauses
referencing arrays while a cursor is open for a query
which references an array.

Database performance and query optimization 197


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

ALLOW_DDL_CHANGES_WHILE_OPEN *DEFAULT The default is set to *NO.


Specifies whether certain DDL operations against a database file The following DDL operations are supported:
are allowed while another user has the database file (or table)
open or a logical file (or view) over a physical file open in another • Trigger operations
job. – SQL CREATE TRIGGER, ALTER TRIGGER, and DROP
TRIGGER
Any open cursors in concurrent jobs that have open
cursors over the target table will continue to operate as
if the operation was not performed until the cursor is
closed.
– SQL COMMENT ON TRIGGER and LABEL ON TRIGGER
statements
There is no effect on concurrent jobs.
– CL ADDPFTRG, RMVPFTRG, and CHGPFTRG commands
Any open cursors in concurrent jobs that have open
cursors over the target table will continue to operate as
if the operation was not performed until the cursor is
closed.
This option is ignored for INSTEAD OF triggers and READ
*YES triggers.
• Grant and revoke operations
– SQL GRANT and REVOKE for database files
Any fully open cursors in concurrent jobs that have open
cursors over the target database file will continue to
operate as if the operation was not performed until the
cursor is closed. If this is not a grant of UPDATE, DELETE,
or INSERT, pseudo-closed cursors in other jobs will not be
closed. Otherwise, all pseudo-closed cursors will be fully
closed.
– GRTOBJAUT and RVKOBJAUT CL commands for database
files
Any fully open cursors in concurrent jobs that have open
cursors over the target database file will continue to
operate as if the operation was not performed until the
cursor is closed. If this is not a grant of *UPD, *DLT, *ADD,
or *EXCLUDE, pseudo-closed cursors in other jobs will not
be closed. Otherwise, all pseudo-closed cursors will be
fully closed.

SQL DDL operations can fail to complete, with an SQL0913 error,


*NO
if an exclusive lock cannot be acquired for the target object.

*DEFAULT The default is set to *YES.


ALLOW_EVI_ONLY_ACCESS Specifies whether encoded vector index RRN probe can be
Specifies whether encoded vector index RRN probe can be *YES considered by the optimizer to replace table accesses. An EVI
considered by the optimizer. must exist for every column being accessed in the table.

*NO Encoded vector index RRN probes cannot replace table access.

*DEFAULT The default value is set to *YES.


ALLOW_TEMPORARY_ INDEXES *YES Allow temporary indexes to be considered.
Specifies whether temporary indexes can be considered by the
optimizer. If temporary indexes are not allowed, then any other Do not allow any temporary indexes to be considered for this
viable plan is chosen regardless of cost to implement this query. access plan. Choose any other implementation regardless of
*ONLY_ REQUIRED
cost to avoid the creation of a temporary index. Only if no viable
plan can be found, is a temporary index allowed.

*DEFAULT The default value is set to *YES.

The CHGQRYA attributes for the job are not applied to the remote
*NO jobs. The remote jobs use the attributes associated to them on
APPLY_REMOTE their systems.
Specifies for database queries involving distributed files, whether
the CHGQRYA query attributes are applied to the jobs on the The query attributes for the job are applied to the remote jobs
remote systems associated with this job. used in processing database queries involving distributed tables.
For attributes where *SYSVAL is specified, the system value
*YES
on the remote system is used for the remote job. This option
requires that, if CHGQRYA was used for this job, the remote jobs
must have authority to use the CHGQRYA command.

198 IBM i: Performance and Query Optimization


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

ASYNC_JOB_USAGE *DEFAULT The default value is set to *LOCAL.


Specifies the circumstances in which asynchronous (temp writer) Asynchronous jobs might be used for database queries that
jobs can be used to help process database queries in the job. The involve only tables local to the system where the database
option determines which types of database queries can be used queries are being run.
in asynchronous jobs (running in parallel) to help complete the
*LOCAL In addition, this option allows the communications required for
query.
queries involving distributed tables to be asynchronous. Each
An asynchronous job is a separate job that handles query requests system involved in the query of the distributed tables can run its
from jobs running the database queries on the system. The portion of the query at the same time (in parallel).
asynchronous job processes each request and puts the results into
a temporary file. This intermediate temporary file is then used by Asynchronous jobs might be used for database queries that
the main job to complete the database query. *DIST
involve distributed tables.
The advantage of an asynchronous job is that it processes its
*ANY Asynchronous jobs might be used for any database query.
request at the same time (in parallel) that the main job processes
another query step. The disadvantage of using an asynchronous No asynchronous jobs are allowed to be used for database
job is that it might encounter a situation that it cannot handle in query processing. In addition, all processing for queries
the same way as the main job. For example, the asynchronous job involving distributed tables occurs synchronously. Therefore, no
might receive an inquiry message from which it cancels, whereas intersystem parallel processing occurs.
the main job can choose to ignore the message and continue.
There are two different types of database queries that can run
asynchronous jobs:
*NONE
1. Distributed queries. These are database queries that involve
distributed files. Distributed files are provided through the
system feature Db2 Multi-System for IBM i.
2. Local queries. there are database queries that involve only
files local to the system where the database queries are being
run.

*DEFAULT The default value is the same as *SYSTEM.

The database manager might cache a query result set. A


CACHE_RESULTS subsequent run of the query by the same job can reuse the
Specifies a way for the user to control the cache results cached result set. Or, if the ODP for the query has been deleted,
processing. For queries involving temporary results, for example, any job can reuse the cached result set.
sorts or hashes, the database manager often saves the results In many cases, this option works well. However, you need to
*SYSTEM
across query pseudo-close or pseudo-open. The results are saved consider if the query is doing work outside of the database
as long as they are not large, with the hope that they can be manager which could affect temporary results. In that case,
reused for the next run of the query. Beginning in V5R3, the *JOB or *NONE may be a more appropriate setting. For example,
database manager saves these temporary results even when a if field procedures that mask data are used or swapping of user
job is finished with them. The database manager assumes that profiles in a UDF can occur, this option should specify *NONE.
another job can later reuse the results.
The database manager automatically controls the caching of these The database manager might cache a query result set from one
results, removing cache results as storage usage becomes large. run to the next for a job. Caching can occur as long as the
However, the amount of temporary storage used by the database *JOB query uses a reusable ODP. When the reusable ODP is deleted,
can be noticeably more than in previous releases. the cached result set is destroyed. This value mimics V5R2
processing.

*NONE The database does not cache any query results.

*DEFAULT The default value is *NO.


COLLATE_ERRORS
Specifies how data errors are handled on the GROUP BY and A value of *NO causes the query to be ended with an error when
*NO
ORDER BY expression during hash or sort processing within a grouping or ordering expressions results in an error.
queries.
*YES A value of *YES indicates that the grouping or sort continues.

*DEFAULT is equivalent to 500,000,000.


If multiple journals are involved in the transaction, the
COMMITMENT_CONTROL_LOCK_LIMIT applies to each journal,
COMMITMENT_CONTROL_LOCK_LIMIT not to the transaction as a whole.
Specifies the maximum number of records that can be locked to a *DEFAULT
For example, files F1 to F5 are journaled to journal
commit transaction initiated after setting the new value. J1, and files F6 to F10 are journaled to J2. The
The value specified for COMMITMENT_CONTROL_LOCK_LIMIT COMMITMENT_CONTROL_LOCK_LIMIT is set to 100,000.
does not affect transactions running in jobs that have already 100,000 record locks can be acquired for files F1 to F5. 100,000
started commitment control. For the value to be effective, it must more locks can be acquired for files F6 to F10.
be changed before starting commitment control.
The maximum number of records that can be locked to a commit
Integer Value transaction initiated after setting the new value.
The valid integer value is 1–500,000,000.

Database performance and query optimization 199


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

*DEFAULT The default value is *OPTIMIZE

Uncommitted changes that delete or update records so that they


*OPTIMIZE are no longer selected by the query will not be considered as
candidates for query synchronization.

All records referenced by a table scan query access plan will


CONCURRENT_ACCESS_BEHAVIOR synchronize with any changes that are not yet committed.
Controls how queries with an isolation level of Cursor Stability (CS) Serialization behavior depends on the concurrent access
or Read Stability (RS) interact with uncommitted table changes. resolution used by the query, for example, SKIP LOCKED
DATA, USE CURRENTLY COMMITTED, or WAIT FOR OUTCOME
*STRICTSCAN (default). Since the table scan attempts to serialize with any
pending transactions for deleted and non-selected records,
query performance will be reduced, as compared to *OPTIMIZE.
Queries may contain many access plan types, but this option is
only supported for table scan access. All other plan types will
use *OPTIMIZE behavior.

DETERMINISTIC_UDF_SCOPE *DEFAULT The default value is *ALWAYS.


Specifies the scope or lifetime of the deterministic setting for The UDF is always considered deterministic. Query temporary
User Defined Functions (UDFs) and User Defined Table Functions *ALWAYS objects might be shared across query opens and the UDF might
(UDTFs). not run for a particular query open.
It is recommended that you specify STATEMENT DETERMINISTIC
*OPEN The UDF is considered deterministic only for a single instance
on any CREATE FUNCTION statement that should be considered
of a query open. Query temporary objects are not shared across
deterministic for a single instance of a query open rather than
query open. The UDF is run at least once in the query for a given
using the *OPEN option. DETERMINISTIC_UDF_SCOPE applies
set of input parameters.
to all deterministic UDFs and UDTFs in every query while this
QAQQINI option is in effect.

*DEFAULT The default value is *ALLOW_EQUAL.

No optimization to remove field procedure decode option


4 or transformations to optimize field procedure invocations
is allowed. For example, the optimizer cannot transform
*NONE
fieldProc(4, column) = ‘literal' to column =
fieldProc(0, ‘literal'). This option is used when the
field procedure is not deterministic.

Optimization allowed for equal and not equal predicates, GROUP


BY, and DISTINCT processing. For example, the optimizer might
FIELDPROC_ENCODED_COMPARISON choose to change the predicate fieldProc(4, column) =
*ALLOW_
Specifies the amount of optimization that the optimizer might use ‘literal' to column = fieldProc(0, ‘literal') in
EQUAL
when queried columns have attached field procedures order to facilitate index matching. This option is useful when
the field procedure is deterministic but no ordering can be
determined based on the result of the field encoding.

Transformation allowed for MIN, MAX grouping functions,


ORDER BY, and all predicates except LIKE in addition to
*ALLOW_
the transformations supported by *ALLOW_EQUAL. This option
RANGE
is useful when the field procedure is deterministic and the
encoded value implies ordering

Transformation allowed for all predicates including LIKE, in


*ALL
addition to the transformations supported by *ALLOW_RANGE.

*DEFAULT The default is set to *NO.

*NO Allow the optimizer to reorder join tables.

Only force the join order for those queries that use the SQL JOIN
*SQL syntax. This option mimics the behavior for the optimizer before
FORCE_JOIN_ORDER V4R4M0.

Specifies to the query optimizer that the join of files is to occur in Only force the join position for the file listed by the numeric
the order specified in the query. *PRIMARY value nnn into the primary position (or dial) for the join. nnn is
nnn optional and defaults to 1. The optimizer then determines the
join order for all the remaining files based upon cost.

Do not allow the query optimizer to specify the order of join


*YES tables as part of its optimization process. The join occurs in the
order in which the tables were specified in the query.

200 IBM i: Performance and Query Optimization


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

*DEFAULT The default value is set to *OPTIMIZE.

When processing the SQL LIKE predicate or OPNQRYF command


%WLDCRD built-in function, redundant shift characters are
ignored for DBCS-Open operands. The optimizer cannot use an
*ALWAYS
index to perform key row positioning for SQL LIKE or OPNQRYF
IGNORE_LIKE_ REDUNDANT_SHIFTS %WLDCRD predicates involving DBCS-Open, DBCS-Either, or
DBCS-Only operands.
Specifies whether redundant shift characters are ignored for
DBCS-Open operands when processing the SQL LIKE predicate or When processing the SQL LIKE predicate or the OPNQRYF
OPNQRYF command %WLDCRD built-in function. command %WLDCRD built-in function, redundant shift
characters might be ignored for DBCS-Open operands. These
characters are ignored depending on whether an index is used to
*OPTIMIZE
perform key row positioning for these predicates. This option
enables the query optimizer to consider key row positioning
for SQL LIKE or OPNQRYF %WLDCRD predicates involving DBCS-
Open, DBCS-Either, or DBCS-Only operands.

*DEFAULT The default value is *OPTIMIZE.

The amount of time used for key range estimate operations is


*OPTIMIZE
determined by the query optimizer.

No time limit is specified for key range estimate operations, and


KEY_RANGE_ESTIMATE_TIMEOUT every estimate will run to completion regardless of the time
*NONE
required. This is the behavior of the query optimizer in releases
Specifies the amount of time the query optimizer may use for any before IBM i 7.3.
individual key range estimate operation. Key range estimates are
used with indexes to approximate the number of rows for a given The number of seconds a key range estimate operation may
predicate. This option may help to reduce the time spent waiting execute before returning an estimate to the query optimizer.
for some queries to complete optimization. At the end of this time interval, the optimizer will continue
optimizing the query, and the estimate operation will continue in
Integer Value a background process. A smaller value may reduce optimization
time but may also cause less accurate estimates to be used by
the optimizer.
Valid values are 1-86400.

LIMIT_PREDICATE_ OPTIMIZATION Do not eliminate the predicates that are not simple isolatable
*DEFAULT
predicates (OIF) when doing index optimization. Same as *NO.
Specifies that the query optimizer can only use simple isolatable
predicates (OIF) when performing its index optimization. Do not eliminate the predicates that are not simple isolatable
*NO
An OIF is a predicate that can eliminate a record without further predicates (OIF) when doing index optimization.
evaluation. Any predicate that cannot be classified as an OIF is
Eliminate the predicates that are not simple isolatable
ignored by the optimizer and needs to be evaluated as a non-key
predicates (OIF) when doing index optimization.
selection predicate.
A=10 and (A => 10 AND B=9) are OIFs. *YES
A=10 OR B=9 are not OIFs.
Note: *YES impairs or limits index optimization.

The default value is set to 0. This option indicates that the


*DEFAULT
database does not free locators.

LOB_LOCATOR_THRESHOLD If the value is 0, then the database does not free locators. For
values 1 through 250,000, on a FETCH request, the database
Specifies either *DEFAULT or an Integer Value -- the threshold to compares the SQL current LOB locator count for the job against
free eligible LOB locators that exist within the job. Integer Value the threshold value. If the locator count is greater than or equal
to the threshold, the database frees host server created locators
that have been retrieved. This option applies to all host server
jobs (QZDASOINIT) and has no impact to other jobs.

*DEFAULT The default value is set to 0.

0 No materialized query tables can be used.


MATERIALIZED_QUERY_ TABLE_REFRESH_AGE
Specifies the ability to examine which materialized query tables Any tables indicated by the MATERIALIZED_
*ANY
are eligible to be used based on the last time a REFRESH TABLE QUERY_TABLE_USAGE INI parameter can be used.
statement was run.
Only tables indicated by MATERIALIZED_ QUERY_TABLE_USAGE
Timestamp_
INI option which have a REFRESH TABLE performed within the
duration
specified timestamp duration can be used.

Database performance and query optimization 201


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

*DEFAULT The default value is set to *NONE.

MATERIALIZED_QUERY_ TABLE_USAGE Materialized query tables cannot be used in query optimization


*NONE
and implementation.
Specifies the usage of materialized query tables in query
optimization and runtime. *ALL User-maintained materialized query tables may be used.

*USER User-maintained materialized query tables can be used.

*DEFAULT The default value is set to *JOB.

Paging is done in the pool of the job. This option is normal paging
*JOB
behavior.

Attempt to page storage into the base pool when paging is


*BASE needed and a database operation that supports targeted paging
MEMORY_POOL_PREFERENCE occurs.
Specifies the preferred memory pool that database operations
uses. This option does not guarantee use of the specified pool, Attempt to page storage into pool nn when paging is needed and
nn
but directs database to perform its paging into this pool when a database operation that supports targeted paging occurs.
supported by the database operation.
Attempt to page storage into a named storage pool when paging
*NAME PoolName is needed and a database operation that supports targeted
paging occurs.

*PRIVATE Attempt to page storage into a private storage pool in specified


Library/Subsystem/ library and subsystem when paging is needed and a database
PoolNumber operation that supports targeted paging occurs.

MESSAGES_DEBUG *DEFAULT The default is set to *NO.


Specifies whether Query Optimizer debug messages are displayed *NO No debug messages are to be displayed.
to the job log. These messages are regularly issued when the job is
in debug mode. *YES Issue all debug messages that are generated for STRDBG.

*DEFAULT The default is set to *NO.


NORMALIZE_DATA
Unicode constants, host variables, parameter markers, and
Specifies whether normalization is performed on Unicode *NO
expressions that combine strings is not normalized.
constants, host variables, parameter markers, and expressions
that combine strings. Unicode constants, host variables, parameter markers, and
*YES
expressions that combine strings is normalized

*DEFAULT *DEFAULT is equivalent to 0. See Integer Value for details.

This value determines the number of cursors to be closed.


The valid values for this parameter are 1 - 65536. The value
for this parameter is less than or equal to the number in the
OPEN_CURSOR_THREHOLD parameter.
If the number of open cursors reaches the value specified by the
OPEN_CURSOR_THRESHOLD, pseudo-closed cursors are hard
OPEN_CURSOR_CLOSE_ COUNT
(fully) closed. The least recently used cursors are closed first.
Specifies either *DEFAULT or an Integer Value: the number of
Integer Value This value is ignored if OPEN_CURSOR_THRESHOLD is
cursors to full close when the threshold is encountered.
*DEFAULT. If OPEN_CURSOR_THRESHOLD is specified and the
value is *DEFAULT, the number of cursors closed is equal
to OPEN_CURSOR_THRESHOLD multiplied by 10 percent. The
result is rounded up to the next integer value.
OPEN_CURSOR_CLOSE_COUNT is used with
OPEN_CURSOR_THRESHOLD to manage the number of open
cursors within a job. Open cursors include pseudo-closed
cursors.

*DEFAULT *DEFAULT is equivalent to 0. See Integer Value for details.

This value determines the threshold to start full close of


pseudo-closed cursors. When the number of open cursors
reaches this threshold value, pseudo-closed cursors are hard
(fully) closed with the least recently used cursors being closed
first. The number of cursors to be closed is determined by
OPEN_CURSOR_ THRESHOLD OPEN_CURSOR_CLOSE_COUNT.
Specifies either *DEFAULT or an Integer Value -- the threshold to The valid user-entered values for this parameter are 1 - 65536.
start full close of pseudo-closed cursors. Integer Value
A default value of 0 indicates that there is no threshold. Hard
closes are not forced based on the number of open cursors
within a job.
OPEN_CURSOR_THRESHOLD is used with
OPEN_CURSOR_CLOSE_COUNT to manage the number of open
cursors within a job. Open cursors include pseudo-closed
cursors.

202 IBM i: Performance and Query Optimization


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

Optimization goal is determined by the interface (ODBC, SQL


*DEFAULT
precompiler options, OPTIMIZE FOR nnn ROWS clause).

All queries are optimized with the goal of returning the first page
of output as fast as possible. This option works well when the
*FIRSTIO output is controlled by a user likely to cancel the query after
OPTIMIZATION_GOAL viewing the first page of data. Queries coded with OPTIMIZE
Specifies the goal that the query optimizer uses when making FOR nnn ROWS honor the goal specified by the clause.
costing decisions.
All queries are optimized with the goal of running the entire
query to completion in the shortest amount of elapsed time. This
option is better when the output of a query is written to a file
*ALLIO
or report, or the interface is queuing the output data. Queries
coded with OPTIMIZE FOR nnn ROWS honor the goal specified
by the clause.

The amount of time spent in gathering index statistics is


*DEFAULT
OPTIMIZE_STATISTIC_ LIMITATION determined by the query optimizer.
Specifies limitations on the statistics gathering phase of the query No index statistics are gathered by the query optimizer. Default
optimizer. *NO
statistics are used for optimization. (Use this option sparingly.)
One of the most time consuming aspects of query optimization is
*PERCENTAGE Specifies the maximum percentage of the index that is searched
in gathering statistics from indexes associated with the queried
integer value while gathering statistics. Valid values for are 1 - 99.
tables. Generally, the larger the size of the tables involved in the
query, the longer the gathering phase of statistics takes.
*MAX_ Specifies the largest table size, in number of rows, for which
This option provides the ability to limit the amount of resources
NUMBER_OF_ gathering statistics is allowed. For tables with more rows than
spend during this phase of optimization. The more resources
RECORDS_ the specified value, the optimizer does not gather statistics and
spent on statistics gathering, the more accurate (optimal) the
ALLOWED uses default values.
optimization plan is.
integer value

Database performance and query optimization 203


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

*DEFAULT The default value is *SYSVAL.

*SYSVAL Set to the current system value QQRYDEGREE.

Any number of tasks can be used. SMP parallel processing is not


allowed.
*IO
The SQE optimizer considers I/O parallelism with or without this
setting.

Any number of tasks for:


• I/O or SMP parallel processing of the query
• database file keyed access path build, rebuild, or
maintenance.
SMP parallel processing is used only if the system feature, Db2
Symmetric Multiprocessing for IBM i, is installed.
Use of parallel processing and the number of tasks used is
PARALLEL_DEGREE determined by:
*OPTIMIZE
Specifies the parallel processing option that can be used when • the number of processors available in the system
running database queries and database file keyed access path • the job share of the amount of active memory available in the
builds, rebuilds, and maintenance in the job. The specified parallel pool in which the job is run
processing option determines the types of parallel processing
allowed. There are two types of parallel processing: • whether the expected elapsed time for the query or database
file keyed access path build or rebuild is limited by CPU
1. Input/Output (I/O) parallel processing. With I/O parallel processing or I/O resources.
processing, the database manager uses multiple tasks for
each query to do the I/O processing. The central processor The query optimizer chooses an implementation that minimizes
unit (CPU) processing is still done serially. elapsed time based on the job share of the memory in the pool.

2. Symmetric Multiprocessing (SMP). SMP assigns both CPU and Like *OPTIMIZE, with the value nnn indicating a percentage
I/O processing to tasks that run the query in parallel. Actual from 1 to 200, used to influence the number of tasks. If not
CPU parallelism requires a system with multiple processors. specified, 100 is used.
SMP can only be used if the system feature, Db2 Symmetric
Multiprocessing, is installed. Use of SMP parallelism can The query optimizer determines the parallel degree for the
affect the order in which records are returned. *OPTIMIZE query using the same processing as is done for *OPTIMIZE.
nnn Once determined, the optimizer adjusts the actual parallel
degree used for the query by the percentage given.
Allows the user to override the parallel degree used
without having to specify a particular parallel degree under
*NUMBER_OF_TASKS.

The query optimizer chooses to use either I/O or SMP parallel


processing to process the query. SMP parallel processing is used
only if the system feature, Db2 Symmetric Multiprocessing for
IBM i, is installed.
nnn is a percentage from 1 to 200 and is used to influence the
nnn number of tasks. If not specified, 100 is used.
The choices made by the query optimizer are like those choices
made for parameter value *OPTIMIZE. The exception is the
assumption that all pool active memory can be used for query
processing, database file keyed access path build, rebuild, or
maintenance.

PARALLEL_DEGREE (continued) *NONE No parallel processing is allowed for database query processing
or database table index build, rebuild, or maintenance.

*NUMBER_ Indicates the maximum number of tasks that can be used for a
OF _TASKS single query. The number of tasks is limited to either this value
nnn or the number of disk arms associated with the table.
Not recommended if running SQE. The SQE optimizer attempts
to use this degree and override many of the normal costing
mechanisms. For SQE, use *OPTIMIZE with a percentage.

*MAX xxx Like *MAX, with the value xxx indicating the ability to specify
an integer percentage value 1 - 200. The query optimizer
determines the parallel degree for the query using the same
processing as is done for *MAX. Once determined, the optimizer
adjusts the actual parallel degree used for the query by
the percentage given. This option provides the user the
ability to override the parallel degree used to some extent
without having to specify a particular parallel degree under
*NUMBER_OF_TASKS.

204 IBM i: Performance and Query Optimization


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

*DEFAULT The default value is set to *YES.


PARAMETER_MARKER_ CONVERSION
Specifies whether to allow literals to be implemented as *NO Constants cannot be implemented as parameter markers.
parameter markers in dynamic SQL queries.
*YES Constants can be implemented as parameter markers.

*DEFAULT The default value is set to *NO

When a job requests an exclusive lock on an object, do not


*NO prevent concurrent jobs from acquiring additional locks on the
PREVENT_ADDITIONAL_CONFLICTING_LOCKS object.
The following SQL DDL statements require an exclusive, no read
lock on the target table. If the application activity cannot be When *YES is chosen, any new requests for these lower-level
quiesced, it can be hard to accomplish these operations. read locks will be kept behind the exclusive lock request and
could surface to applications as the table is unavailable for use
The PREVENT_ADDITIONAL_CONFLICTING_LOCKS QAQQINI
for querying.
option provides a control for customers to use to direct the
operating system to favor a request for an exclusive, no read lock *YES • ALTER TABLE (Add, Alter or Drop Column)
over new requests to lock the object for reading.
• CREATE TRIGGER
• LOCK TABLE
• RENAME TABLE

*DEFAULT The default value is set to *NO

The optimizer does not check host variables for selectivity


*NO
changes once in pseudo-open.
PSEUDO_OPEN_CHECK_HOST_VARS
This option can be used to allow SQE to check the selectivity of the The optimizer will determine when a host variable selectivity
host variable values at pseudo open time. If the new set of host should be checked. In general, the optimizer will monitor the
variable values require a different plan to perform well, SQE will query and if after a certain number of runs it determines that
*OPTIMIZE
re-optimize the query. there is no advantage to checking host variable selectivity at
pseudo open time, it will stop checking. Full opens do normal
This option is most appropriate when there is considerable plan validation.
variability in the selectivity of host variable in the queries
predicates. The optimizer will always check host variable selectivity at
pseudo open time.
*YES
Note: If the REOPTIMIZE_ACCESS_PLAN INI option is set to
*ONLY_REQUIRED then this INI option has no effect.

*DEFAULT The default value is set to *SYSVAL.

The query time limit for this job is obtained from the system
*SYSVAL
value, QQRYTIMLMT.
QUERY_TIME_LIMIT
Specifies a time limit for database queries allowed to be started *NOMAX There is no maximum number of estimated elapsed seconds.
based on the estimated number of elapsed seconds that the query
Specifies the maximum value that is checked against the
requires to process.
estimated number of elapsed seconds required to run a
integer value query. If the estimated elapsed seconds are greater than this
value, the query is not started. Valid values range from 0 to
2,147,352,578.

*DEFAULT The default value is set to *NO.


REOPTIMIZE_ACCESS_PLAN
Do not force the existing query to be reoptimized. However, if the
Specifies whether the query optimizer reoptimizes a query with a *NO optimizer determines that optimization is necessary, the query is
saved access plan. optimized.
Queries can have a saved access plan stored in the associated
storage of an HLL program, or in the plan cache managed by the *YES Force the existing query to be reoptimized.
optimizer itself.
*FORCE Force the existing query to be reoptimized.
Note: If you specify *NO the query could still be revalidated.
Do not allow the plan to be reoptimized for any subjective
Some of the reasons this option might be necessary are: reasons. For these cases, continue to use the existing plan since
• The queried file was deleted and recreated. it is still a valid workable plan. This option could mean that you
*ONLY_ might not get all the performance benefits that a reoptimization
• The query was restored to a different system than the one on
REQUIRED plan might derive. Subjective reasons include file size changes,
which it was created.
new indexes, and so on. Non-subjective reasons include deletion
• An OVRDBF command was used. of an index used by existing access plan, query file being deleted
and recreated, and so on.

Database performance and query optimization 205


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

*DEFAULT Normal positioning behavior is performed.

*NO_ROLLBACK The current cursor position is unchanged by a rollback.


_HOLD
SQE_NATIVE_ACCESS_POSITION_BEHAVIOR
If an attempted key positioning operation fails,the cursor
This option controls the positioning behavior of native opens or position prior to the attempted operation will not be restored.
queries implemented by SQE. By specifying an option other than *NO_KEY_
It is assumed that another absolute positioning operation, such
*DEFAULT, performance benefits may be realized. FAILURE_HOLD
as first, last, or key equal, will be attempted before any relative
positioning operations, such as next or previous.

Behavior is the same as defined for *NO_ROLLBACK_HOLD and


*NO_HOLD
*NO_KEY_FAILURE_HOLD values.

SQLSTANDARDS_MIXED_ CONSTANT *DEFAULT The default value is set to *YES.

Specifies whether to allow IGC constants to always be treated as *YES SQL IGC constants are treated as IGC-OPEN constants.
IGC-OPEN in SQL queries.
If the data in the IGC constant only contains shift-out DBCS-data
Note: When *NO is specified, Db2 for i is not compatible with the *NO shift-in, then the constant are treated as IGC-ONLY, otherwise it
other Db2 platforms. is treated as IGC-OPEN.

*DEFAULT The default value is set to *WAIT.

The database manager must wait for the commit or rollback


when encountering data in the process of being updated,
deleted, or inserted. Rows encountered that are in the process
*WAIT
of being inserted are not skipped. This option applies if possible
SQL_CONCURRENT_ACCESS_RESOLUTION when the isolation level in effect is Cursor Stability or Read
Specifies the concurrent access resolution to use for an SQL query. Stability and is ignored otherwise.

The database manager can use the currently committed version


of the data for read-only scans when it is in the process of being
*CURCMT updated or deleted. Rows in the process of being inserted can
be skipped. This option applies if possible when the isolation
level in effect is Cursor Stability and is ignored otherwise.

SQL_DECFLOAT_WARNINGS *DEFAULT The default value is set to *NO.


Specifies the warnings returned for SQL DECFLOAT computations A warning is returned to the caller for DECFLOAT computations
and conversions involving: *YES and conversions involving division by 0, overflow, underflow,
• division by 0. invalid operand, inexact result, or subnormal number.

• overflow. An error or a mapping error is returned to the


• underflow. caller for DECFLOAT computations and
conversions involving division by 0, overflow,
• an invalid operand. *NO underflow, or an invalid operand.
• an inexact result.
A warning or error is not returned for an inexact result or a
• subnormal number.

The default value is set to 0.


0 indicates that the database manager chooses how many rows
to consider when determining whether fast delete could be used
instead of traditional delete.
*DEFAULT
When using the default value, the database manager will most
likely use 1000 as a row count. This means that using the INI
option with a value of 1000 results in no operational difference
SQL_FAST_DELETE_ROW_COUNT from using 0 for the option.

Specifies how the delete is implemented by the database This value forces the database manager to never attempt to fast
*NONE
manager. This value is used when processing a DELETE FROM delete on the rows.
table-name SQL statement without a WHERE clause.
*OPTIMIZE This value is same as using *DEFAULT.

Specifying a value for this option allows the user to tune the
behavior of DELETE. The target table for the DELETE statement
must match or exceed the number of rows specified on the
Integer Value option for fast delete to be attempted. A fast delete does not
write individual rows into a journal.
The valid values are 1 - 999,999,999,999,999.

206 IBM i: Performance and Query Optimization


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

*DEFAULT The default value is set to *DEFER

Global variables do not need to exist when an SQL routine is


created or the SQL pre-compiler is run. Since global variables
SQL_GVAR_BUILD_RULE
are not required to exist, the create will not fail when an
*DEFER
Determines whether global variables must exist or not when incorrect column name or routine variable is encountered.
building SQL routines or executing SQL pre-compiles. Incorrect name usage will result in SQL0206 - "Column or global
variable &1 not found." failures when the statement is executed.
This option has no affect on dynamic SQL statements.
*EXIST Global variables referenced by SQL must exist when the SQL
routine is created or the SQL pre-compiler is run. Using this
option, an SQL0206 will be issued at create time.

SQL_MODIFIES_SQL_DATA *DEFAULT The default value is set to *NO.


From the SQL Standard, no MODIFIES SQL DATA operations are No MODIFIES SQL DATA operations are allowed in an SQL
allowed in an SQL BEFORE trigger. *NO
BEFORE trigger.
The Informix® database allows MODIFIES SQL DATA operations
MODIFIES SQL DATA operations are allowed in an SQL BEFORE
in SQL BEFORE triggers. Setting the option to *YES allows
*YES trigger.
SQL BEFORE triggers to perform the SQL MODIFIES SQL DATA
operations.

SQL_PSEUDO_CLOSE The default behavior depends upon whether the QSQPSCLS1


*DTAARA exists.
Before V6R1: SQL cursor open processing checks for the presence
of a data area named QSQPSCLS1 in the library list of the job. If the QSQPSCLS1 *DTAARA was found on the first OPEN within
If the data area is found, all reusable cursors are marked as the job, then SQL cursors are marked as candidates for reuse.
*DEFAULT
candidates for reuse. They are pseudo-closed the first time rather The cursors are pseudo-closed on the first close.
than the second time the application closes the cursor. Without
If the QSQPSCLS1 *DTAARA was not found on the first OPEN
this data area, a cursor does not become reusable until the second
within the job, then SQL cursors are marked as candidates for
close.
reuse. The cursors are pseudo-closed on the second close.
Pseudo-closing the first time results in leaving some cursors open
that might not be reused. These open cursors can increase the Specifies a value greater than zero that indicates when a cursor
amount of auxiliary and main storage required for the application. is pseudo-closed. The value of this option minus 1 indicates how
The storage can be monitored using the WRKSYSSTS command. many times the cursor is hard closed before being marked as
For the amount of auxiliary storage used, look at the "% system candidate for pseudo-close. Valid values are 1 - 65535.
ASP used." For the amount of main storage, examine the faulting
rates on the WRKSYSSTS display.
The format and the contents of the data area are not important.
The data area can be deleted using the following command: Integer Value
DLTDTAARA DTAARA(QGPL/QSQPSCLS1).
The existence of the data area is checked during the first SQL open
operation for each job. It is checked only once and the processing
mode remains the same for the life of the job. Because the library
list is used for the search, the change can be isolated to specific
jobs. Create the data area in a library that is included only in the
library lists for those jobs.

The default value is set to 2. The default indicates that the


access plan associated with any statement will be removed
*DEFAULT
after a statement has been compressed twice without being
SQL_STMT_COMPRESS_MAX executed.

Specifies the compression maximum setting, which is used when The integer value represents the number of times that a
statements are prepared into a package. statement is compressed before the access plan is removed to
Integer Value create more space in the package. Executing the SQL statement
resets the count for that statement to 0. The valid Integer values
are 1 - 255.

SQL_STMT_REUSE The default value is 3. The statement is stored on the third


*DEFAULT
prepare of the statement.
Specifies the number of times the statement must be prepared
in the same connection before the statement is stored in the SQL 1::255 The number of times the statement must be prepared in the
extended dynamic package. If the number of times the statement same connection before the statement is stored in the SQL
has been prepared in the same connection is less than the package.
specified INI option, a temporary copy of the statement is used.
Any other job preparing the statement does a complete prepare.

Database performance and query optimization 207


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

*DEFAULT The default value is set to *NO.

If masked data is being used to insert into or update a table,


*YES detection of this masked data will not be done and a SQ20478
with reason code 30 will not be sent.
SQL_SUPPRESS_MASKED_DATA_DETECTION
If masked data is being used to insert into or update a table
with activated column access control directly from an expression
*NO involving a column with an active column mask, detection of this
masked data will be done and a SQ20478 with reason code 30
will be sent.

*DEFAULT The default value is set to *NO.

Examine the SQLCODE in the SQLCA after execution of a


statement. If the SQLCODE is one of the listed warnings, then
alter the SQLCA so that no warning is returned to the caller.
Set the SQLCODE to 0, the SQLSTATE to '00000' and SQLWARN
SQL_SUPPRESS_WARNINGS to ' '.

For SQL statements, this parameter provides the ability to *YES Warnings:
suppress SQL warnings. • SQL0030
• SQL0335
• SQL0387
• SQL7909 (on a DROP PROCEDURE/ROUTINE/FUNCTION)

*NO Specifies that SQL warnings are returned to the caller.

SQL_TRANSLATE_ASCII_ TO_JOB *DEFAULT The default value is set to *NO.


Specifies whether to translate SQL statement text on the Translate ASCII SQL statement text to the CCSID of the IBM i
application server (AS) according to the CCSID of the job. This *YES
job.
option applies when using DRDA to connect to an IBM i as the AS
where the application requestor (AR) machine is an ASCII-based Translate ASCII SQL statement text to the EBCIDIC CCSID
*NO
platform. associated with the ASCII CCSID.

*DEFAULT The default value is set to 1208.

The job CCSID is used for XML columns, host variables,


SQL_XML_DATA_CCSID
*JOB parameter markers, and expressions, if not explicitly specified.
Specifies the CCSID to be used for XML columns, host variables, If the job CCSID is 65535, the default CCSID of 1208 is used.
parameter markers, and expressions, if not explicitly specified.
The CCSID used for XML columns, host variables, parameter
See “SQL_XML_DATA_CCSID QAQQINI option” on page 210 markers, and expressions, if not explicitly specified. This value
Integer Value
must be a valid single-byte or mixed EBCDIC CCSID or Unicode
CCSID. The value cannot be 65535.

STAR_JOIN *DEFAULT The default value is set to *NO


Note: Only modifies the environment for the Classic Query Engine. *NO The EVI Star Join optimization support is not enabled.
Specifies enhanced optimization for hash queries where both a
Allow query optimization to cost the usage of EVI Star Join
hash join table and a Distinct List of values is constructed from
support.
the data. This Distinct List of values is appended to the selection
against the primary table of the hash join The optimizer determines whether the Distinct List selection is
used based on how much benefit can be derived from using that
Any EVI indexes built over these foreign key columns can be used
selection.
to perform bitmap selection against the table before matching the *COST
join values.
The use of this option does not guarantee that star join is chosen
by the optimizer. It only allows the use of this technique if the
optimizer has decided to implement the query by using a hash
join.

*DEFAULT The default value is set to *NOMAX.

*NOMAX Never stop a query from running because of storage concerns.


STORAGE_LIMIT
The maximum amount of temporary storage in megabytes that
Specifies a temporary storage limit for database queries. If a query can be used by a query. This value is checked against the
is expected to use more than the specified amount of storage, the estimated amount of temporary storage required to run the
query is not allowed to run. The value specified is in megabytes. Integer Value query as calculated by the query optimizer. If the estimated
amount of temporary storage is greater than this value, the
query is not started. Valid values range from 0 through
2147352578.

208 IBM i: Performance and Query Optimization


Table 51. Query Options Specified on QAQQINI Command (continued)

Parameter Value Description

SUPPRESS_INQUIRY_MESSAGES *DEFAULT The default value is set to *NO.


Specifies that certain inquiry messages will not be issued. System inquiry message CPA32B2 will not be issued when
*YES
altering a table.

*NO No system inquiry messages will be suppressed.

*DEFAULT The default value is set to *YES.

Examine the system-wide SQL Statement Cache when an SQL


SYSTEM_SQL_STATEMENT_ CACHE prepare request is processed. If a matching statement exists in
*YES
Specifies whether to disable the system-wide SQL Statement the cache, use the results of that prepare. This option allows the
Cache for SQL queries. application to potentially have better performing prepares.

Specifies that the system-wide SQL Statement Cache is not


*NO
examined when processing an SQL prepare request.

*DEFAULT The default value is set to *ERROR.

*ERROR An SQ20528 error will be signaled.


SYSTIME_PERIOD_ADJ
These three things will happen:
For update and delete operations involving system-period
1. The row end value of the history row will be set to the row
temporal tables, this option resolves conflict for a historical row
begin value plus a small delta of one microsecond.
when its row end value could be less than its row begin value. *ADJUST
2. The row begin value of the temporal table current row will
also be set to the adjusted value.
3. An SQL warning SQ20528 will be signaled.

Use the default as defined by database. This option is equivalent


*DEFAULT
to UTC.

TEXT_SEARCH_DEFAULT_TIMEZONE A time zone formatted value where

Specifies the time zone to apply to any date or dateTime value • s is the sign, + or –
specified in an XML text search using the CONTAINS or SCORE • HH is the hour
function. The time zone is the offset from UTC (Greenwich mean
sHH:MM • MM is the minute
time. It is only applicable when a specific time zone is not given for
the value. The valid range for HH is 00 - 23. The valid range for MM is 00
- 59. The format is specific. All values are required, including
sign. If HH or MM is less than 10, it must have a leading zero
specified.

The amount of time to wait is determined by the database. The


*DEFAULT
default is 30 seconds.
UDF_TIME_OUT
The maximum amount of time that the database waits for the
*MAX
Note: Only modifies the environment for the Classic Query Engine. UDF to finish.
Specifies the amount of time, in seconds, that the database waits Specify the number of seconds that the database waits for a UDF
for a User Defined Function (UDF) to finish processing. to finish. If the value given exceeds the database maximum wait
integer value
time, the maximum wait time is used by the database. Minimum
value is 1 and maximum value is system defined.

*DEFAULT The default value is set to *YES.

Enables aggressive optimization of variable-length columns,


including index-only access. It also allows constant value
substitution when an equal predicate is present against the
VARIABLE_LENGTH_ OPTIMIZATION columns. As a consequence, the length of the data returned for
Specifies whether aggressive optimization techniques are used on *YES the variable-length column might not include any trailing blanks
variable length columns. that existed in the original data. As a result, the application can
receive the substituted value back instead of the original data.
Function calls could operate on the substituted value instead of
the original string value.

*NO Do not allow aggressive optimization of variable length columns.

Note: The following QAQQINI options will be ignored for SQE native query access. These options were
previously honored for CQE native query access.
• LIMIT_PREDICATE_OPTIMIZATION
• STAR_JOIN
• UDF_TIME_OUT

Database performance and query optimization 209


Note: The following QAQQINI options will be honored for SQE native query access. These options were
previously ignored for CQE native query access.
• DETERMINISTIC_UDF_SCOPE
• FIELDPROC_ENCODED_COMPARISON
• MATERIALIZED_QUERY_TABLE_USAGE
• MATERIALIZED_QUERY_TABLE_REFRESH_AGE
• MEMORY_POOL_PREFERENCE
• VARIABLE_LENGTH_OPTIMIZATION

SQL_XML_DATA_CCSID QAQQINI option


The SQL_XML_DATA_CCSID QAQQINI option has several settings that affect SQL processing.
The SQL_XML_DATA_CCSID QAQQINI setting is applied within SQL in the following SQL processing:

Table 52. SQL_XML_DATA_CCSID setting application within SQL


SQL Processing item Description
Valid values for the QAQQINI option are Valid values are all EBCDIC SBCS and mixed CCSIDs, and
CCSIDs allowed on an XML column. Unicode 1208, 1200, and 13488 CCSIDs.
Does not affect the promotion of SQL data Other SQL data types cannot be directly promoted to the SQL
types. XML data type.
XMLPARSE untyped parameter markers. The QAQQINI setting applies to untyped parameter markers
passed as string-expression. The type is CLOB(2G) for SBCS,
mixed, and UTF-8 values. The type is DBCLOB(1G) for Unicode
1200 and 13488.
XMLCOMMENT, XMLTEXT, XMLPI untyped The QAQQINI setting applies to untyped parameter markers
parameter markers. passed as string-expression. The type is VARCHAR(32740)
for SBCS, mixed, and UTF-8 values. The type is
VARGRAPHIC(16370) for Unicode 1200 and 13488.
Applies to parameter marker casts to Applies to an untyped parameter marker passed as an XML-
the XML type for XMLCONCAT, and expression. Unless an explicit CCSID clause is specified, the
XMLDOCUMENT. CCSID of the parameter marker is obtained from the QAQQINI
setting.
The QAQQINI setting does not affect storage The CCSID of the host variables and table columns apply.
and retrieval assignment rules.
String to column assignment on SQL INSERT An implicit or explicit XMLPARSE is required on the column
and UPDATE. assignment.
String to host variable assignment. An implicit or explicit XMLSERIALIZE is required on the host
variable assignment.
Column to column assignment. When the target column is XML, an implicit XMLPARSE is
applied if the source column is not XML. The target XML column
has a defined XML CCSID. When the source column is XML, an
explicit XMLSERIALIZE is required if the target column is not
XML.
Host variable to column assignment. The target column has a defined CCSID.
UNION ALL (if XML publishing functions in The XML result CCSID is obtained from the QAQQINI setting.
query).
Does not apply to SQL constants. UX constants are defined as UTF-16. FX constants are defined
as UTF-8.

210 IBM i: Performance and Query Optimization


Table 52. SQL_XML_DATA_CCSID setting application within SQL (continued)
SQL Processing item Description
Result type of XML data built-in functions. If the first operand of XMLPARSE and XMLVALIDATE is an
untyped parameter marker, the CCSID is set from the QAQQINI
setting, which then affects the XML result CCSID. The QAQQINI
setting is used for XMLSERIALIZE for CHAR, VARCHAR, and
LOB AS data-type. UTF-16 is used for GRAPHIC, DBCLOB, and
NCHAR.
Result type of XML publishing The XML result CCSID for XML publishing functions is obtained
functions - XMLAGG, XMLGROUP, from the QAQQINI setting.
XMLATTRIBUTES, XMLCOMMENT,
XMLCONCAT, XMLDOCUMENT, XMELEMENT,
XMLFOREST, XMLNAMESPACES, XMLPI,
XMLROW, and XMLTEXT.
Result type of XML publishing functions in a The XML result CCSID is set when the view is created.
view.
XML data type on external procedure XML AS The XML parameter CCSID is set when the procedure is created.
parameters.
XML data type on external user-defined The XML parameter and result CCSID are set when the function
functions. is created.
CREATE TABLE XML column. The QAQQINI setting is used for dynamic SQL. The QAQQINI
setting is set in *PGM, *SRVPGM, and *SQLPKG objects when
created.
MQTs containing select-statement with XML The CCSID is set when the MQT is created. The CCSID is
publishing functions. maintained for an ALTER TABLE.
ALTER TABLE ADD MATERIALIZED QUERY The QAQQINI setting is used if the select-statement contains
definition. XML publishing functions.
XML AS CLOB CCSID The QAQQINI setting is built into *PGM and *SRVPGM objects
when the program is created. The CCSID defaults to UTF-8 for
CLOB when QAQQINI setting is UTF-16 or UCS2.
XML AS DBCLOB CCSID The default for DBCLOB is always UTF-16 for XML.
SQL GET and SET DESCRIPTOR XML data QAQQINI setting applied to XML data type.
type.
SQL Global variables. QAQQINI setting applied to global variables with the XML data
type.

Related information
XML values
SQL statements and SQL/XML functions

Query Supervisor
The Db2 for i SQL Query Engine (SQE) provides a Query Supervisor which enables real-time monitoring of
resource consumption by SQL and native queries, for example the Open Query File (OPNQRYF) command.
Query Supervisor threshold levels can be established for general or specific scenarios. When a threshold
is met or exceeded, the query execution is interrupted, and user-supplied exit program(s) are called.

Database performance and query optimization 211


Using Query Supervisor to monitor query resource usage
The Query Supervisor enables monitoring and management of queries that reach pre-determined
thresholds of resource consumption. Unlike the Predictive Query Governor, which intervenes on the basis
of estimated resource usage before a query runs, the Query Supervisor reacts to actual resource usage
while the query runs.
The Query Supervisor monitors any SQL queries that are run to implement user SQL statements,
including native database queries that are processed by SQE. SQL statements that do not require query
processing such as a simple INSERT (for example, INSERT INTO <table> VALUES(123) ) or COMMIT are
not monitored by the Query Supervisor. Query supervision does not occur for queries initiated by the IBM i
operating system or for SQL that has been classified as specific to operating system processing.
The Query Supervisor allows a Database Engineer (DBE) to:
• Deploy real-time notification solutions when a query exceeds a specific resource threshold
• Take actions to terminate queries based on real-time query consumption of system resources
• Capture and log performance details for long-running queries
By configuring the Query Supervisor, a DBE can proactively manage excessive resource usage, monitor for
unexpected workload variation, and automatically end run-away queries. The Query Supervisor provides
the infrastructure for establishing and detecting thresholds. The specific action(s) taken when a threshold
is reached is determined by one or more exit programs that the DBE provides.

Query Supervisor configuration and operation


Multiple thresholds can be defined across the system for various resource types and can apply to all
queries or be restricted to specific users, jobs, and subsystems.
Query Supervisor thresholds are configured using the add and remove procedures:
“ADD_QUERY_THRESHOLD procedure” on page 341 and “REMOVE_QUERY_THRESHOLD procedure” on
page 353. The “QUERY_SUPERVISOR view” on page 351 shows the defined thresholds.
The four threshold types which can be monitored by the Query Supervisor are:
1. CPU Time – The total processing unit time used by the query, in seconds
2. Elapsed Time – The total clock time, in seconds
3. Temporary storage – The amount of storage, in megabytes (MB), that the query uses
4. Total I/O count – The total number of I/O operations
Before a query runs, a list of applicable thresholds is passed to SQE. As the query executes, SQE
monitors the resource usage and determines if a threshold has been reached. When a threshold is met or
exceeded, the query execution is interrupted and any exit programs registered with the Query Supervisor
Exit Point (QIBM_QQQ_QRY_SUPER) are called in sequence of their exit program registration number,
from lowest to highest. The exit program is called inline within the same thread of the query that reached
the threshold. As a result, the query is interrupted and paused until the exit program processing has
completed.
Information passed to the exit programs includes details such as the threshold reached, the job name, the
SQL statement or native query request, the client special register values, and host variable or parameter
marker values. The structure passed to the exit program includes enough detail to allow the DBE to
take a wide variety of actions, such as logging the information, sending a message, or retrieving detailed
information about the query from the plan cache.
The exit program also has the option to indicate that the query should be terminated. If query termination
is requested, no further exit programs are called, and the Query Supervisor issues a CPF5209 escape
message with reason code 3. SQL statements will fail with SQLCODE -666 and SQLSTATE 57005.
If query termination is not requested, execution of the query resumes after all the registered exit
programs have completed. It is possible for multiple, distinct thresholds to be reached simultaneously, in
which case multiple calls to the exit programs will be made before the query resumes.

212 IBM i: Performance and Query Optimization


Resource usage is measured only for processing that the query engine performs while producing the
query result set. It does not apply to other database or operating system processing that happens in
conjunction with the operation. Consider the following SQL DELETE statement: DELETE FROM <table>
WHERE <column> <= 100. Query supervision only applies to the system resources used to determine
the rows selected by the WHERE predicate. The resources consumed by the deletion of rows, journal
processing, and any associated index maintenance for the DELETE are not supervised.
The Query Supervisor will also supervise queries executed as part of a user-defined function (UDF) or
user-defined table function (UDTF) invocation when the reference to that function is not inlined. When a
query uses a function, the Query Supervisor independently supervises the resources consumed by any
queries run during execution of the function. Resources consumed by the invoking query prior to the
function invocation are not counted as part of the resources used by the function’s queries; the resource
usage counters for each query within the function start at 0. However, resources consumed by the queries
within the function are added to the resource usage totals for the invoking query.
Any threshold that is applied to the function’s queries and that is met while the function is executing will
cause the exit program(s) to be called at that point in time. However, when a threshold that is applied
to the invoking query is met while a function is running, the exit program call will be delayed until the
function completes and the invoking query continues executing.
Consider a TOTAL IO COUNT threshold of 500 I/Os and a query that invokes a function that executes
another query. Assume the invoking query consumes 400 I/Os and then invokes the function, whose
query consumes 200 I/Os. The exit program will be called for the invoking query but only after the
function completes. However, if the function's query consumes 500 I/Os, it is possible (subject to the
threshold’s DETECTION_FREQUENCY) that the exit program could be called both within the function
execution (with 500 I/Os) and for the invoking query (with 900 I/Os) once the function completes.
In general, resource usage is checked on sub-second intervals while SQE is processing the query. As a
result, there may be a small delay between when the query reaches a threshold and when the query
supervisor detects this and calls the exit program. The delay is most likely to affect TOTAL IO COUNT
and TEMPORARY STORAGE thresholds and may result in threshold consumption values that exceed the
defined threshold value. Certain operations within the query engine, such as queries containing UDF calls
as described above, can produce a more measurable delay that affects all threshold types. In all cases,
however, the exit program will eventually be called and will be provided with the accurate and current
resource consumption detail.
A specific Query Supervisor threshold will apply at most one time for each query execution within a
thread. For example, a threshold defined for ELAPSED TIME of 5 seconds is reached only at the first 5
seconds of a query’s execution and not repeatedly at further intervals of 5 seconds while the query runs.

Managing Query Supervisor activity


To make it easier to identify any Query Supervisor exit program problems, the first occurrence of an exit
program failure each day will be noted with a CPD43B0 message sent to QSYSOPR.
Any misconfiguration or exit program failures are tolerated and will not affect the supervised query. The
CPD43B0 message allows the DBE to easily recognize that the exit program processing is failing.
In the following figure, the exit program was registered, but the *PGM did not exist with the specified
library and program name. As shown below, the CPD43B0 second level text includes the threshold name,
the exit program library and name, the job that encountered the exit program problem, and the message
identifier related to the exit program failure.

Database performance and query optimization 213


Figure 7. CPD43B0 message in QSYSOPR highlights an exit program setup problem

Summary information about the Query Supervisor’s behavior is available in the SQE Plan Cache Properties
which are accessed with the IBM i Access Client Solutions (ACS) SQL Performance Center. The properties
can also be retrieved using “DUMP_PLAN_CACHE_PROPERTIES procedure” on page 359. The properties
show the number of times since the last IPL that a Query Supervisor threshold has been reached along
with the most recent job and time that the threshold was reached. Similar information is provided for the
most recent instance of a Query Supervisor exit program that directed SQE to terminate a query. Finally, if
there is a problem with the configuration or execution of an exit program, the most recent job and time of
the failure is noted.
These Query Supervisor metrics are provided to give the database engineer (DBE) a basic understanding
of whether thresholds are being encountered, whether queries are being terminated, and whether any
exit program failures exist. The following figure illustrates the query supervision summary metrics.

Figure 8. SQE Plan Cache properties include Query Supervisor detail

Using DETECTION_FREQUENCY to protect system resources


Because the Query Supervisor may be the first line of detection and defense against a critical
performance problem, it is important to make the operation of the Query Supervisor as light-weight as
possible. For this reason, each threshold has a DETECTION_FREQUENCY associated with it. This value,
which defaults to 600 seconds (10 minutes), indicates how much time a given thread must wait after
detecting the threshold before it may detect and signal the same threshold again. If the threshold is
exceeded again in the thread before the defined interval is completed, the threshold will be ignored, and
the exit program(s) will not be called.
Note that the DETECTION_FREQUENCY applies to multiple occurrences of a specific threshold within the
same thread.
Consider a single threaded job, JOB1, which is executing queries. The following thresholds are defined:
• THRESHOLD_NAME => 'WARNING'
THRESHOLD_TYPE => 'ELAPSED TIME'

214 IBM i: Performance and Query Optimization


THRESHOLD_VALUE => 10
DETECTION_FREQUENCY => 600
• THRESHOLD_NAME => 'RUNAWAY'
THRESHOLD_TYPE => 'ELAPSED TIME'
THRESHOLD_VALUE => 120
DETECTION_FREQUENCY => 600
The following example timeline shows the impact of DETECTION_FREQUENCY:

00:00:00 JOB1 begins a query that will take 20 seconds to complete.


00:00:10 Query Supervisor calls the exit program in JOB1. The exit program input structure includes
the name of the threshold: WARNING.
The WARNING threshold will be silenced for any future queries in JOB1 for 600 seconds, until
00:10:10.

00:00:30 JOB1 begins another query that runs for 25 seconds.


No Query Supervisor action is taken after 10 seconds of execution since the WARNING
threshold's DETECTION_FREQUENCY time interval has not been met.

00:01:05 JOB1 begins a query that runs for 215 seconds.


00:03:05 Query Supervisor calls the exit program in JOB1. The exit program input structure includes
the name of the threshold: RUNAWAY.
The RUNAWAY threshold will be silenced for any future queries in JOB1 for 600 seconds, until
00:13:05.

00:09:59 JOB1 begins a query that will run for 50 seconds.


No Query Supervisor action is taken after 10 seconds of execution since the WARNING
threshold's DETECTION_FREQUENCY time interval has not been met. Since the threshold
value is detected while reporting is silenced, this query will not call the exit program for the
WARNING threshold.

A DETECTION_FREQUENCY of 0 is permitted, in which case every instance of the threshold is processed


by a call to the exit program(s).

Writing a Query Supervisor exit program


A well-written exit program is the key to making the Query Supervisor effective. Each time a threshold
is reached, the exit program receives information about the threshold, the job, and the query. The exit
program can take action based on this information, including the option to terminate the query.
Because exit programs run inline and interrupt the query execution, it is recommended that the exit
program should be as simple as possible. When more complex operations are required of the exit
program, it is suggested that they be done asynchronously by passing information to another job for
processing. By doing this, the exit program can complete faster, allowing the query to resume execution.
Some possible operations an exit program can perform are:
• Send an inquiry message, suspending the thread (and query) until a reply is received
• Send the query text, host variables, and parameter markers to another job to be logged to a database
table for future review and analysis
• Terminate the query
SQL and native database I/O must not be run within an exit program. However, it is possible to run SQL
native database I/O in a separate job. Some useful SQL operations include:
• Send a message to QSYSOPR using the QSYS2.SEND_MESSAGE procedure. See “SEND_MESSAGE
procedure ” on page 858 for details.

Database performance and query optimization 215


1. The exit program can send the message using the SQL7064 message identifier which has been
defined for Query Supervisor notifications. The message is in the QSYS/QSQLMSG message file and
has a severity level of 80.
2. Alternatively, the exit program can send the message with a user created message identifier.
• Dump information about the plan for the query that was running when the exit program was called. The
plan identifier that is part of the exit program data can be passed on the call to this procedure. See
“DUMP_PLAN_CACHE procedure” on page 357 for details.
• Use INSERT or MERGE statements to maintain a log of expensive queries.
• Push details regarding the query supervision event to external systems management solutions.
Any messages generated by a failure to call the exit program or by an unhandled exception within the exit
program will appear in the job log of the job that caused the threshold criteria to be met.

Query Supervisor example exit programs


The exit programs in this section demonstrate some of the ways an exit program can be used when a
Query Supervisor threshold is reached. They are provided to enable quick and easy adoption of Query
Supervisor.
The details of the exit program interface can be found here: Query Supervisor Exit Program

Exit program to send message to QSYSOPR


This Query Supervisor exit program sends an informational message to the QSYSOPR message queue.
This program sends an SQL7064 message to the QSYSOPR message queue when it is called for any
threshold. Because SQL cannot be used directly in the exit program, the Run SQL (RUNSQL) CL command
is submitted as a batch job.
The SQL7064 message ID is provided to be used with Query Supervisor. The caller provides a string
containing the text for the message. In this example, the threshold name and the job name that reached
the threshold are included in the message.

ILE RPG exit program to send message to QSYSOPR


This Query Supervisor exit program sends an informational message to the QSYSOPR message queue.
To compile this ILE RPG program, use the following command.

CRTBNDRPG PGM(SUPERVISOR/QS_SENDMSG) SRCFILE(SUPERVISOR/QRPGLESRC)

If CRTRPGMOD and CRTPGM are used to compile and build the program, be sure to include
USRPRF(*OWNER) and ACTGRP(*CALLER) on the CRTPGM command.
The program can be registered as an exit program using this command:

ADDEXITPGM EXITPNT(QIBM_QQQ_QRY_SUPER) FORMAT(QRYS0100) PGMNBR(*LOW) PGM(SUPERVISOR/QS_SENDMSG)


THDSAFE(*YES) TEXT('Query Supervisor send message to QSYSOPR')

By including the THREAD, USRPRF, DFTACTGRP, and ACTGRP options in the source, they can be omitted
on the compiler command. By using USRPRF(*OWNER), *PUBLIC does not need to be given access to
the objects used by this program. The owning profile of the created program must have authority to the
commands and objects used by the exit program. The program uses THREAD(*CONCURRENT) to ensure
thread safety. The program will run in the activation group of the caller.

**free
ctl-opt main(QS_sendmsg);
ctl-opt ccsid(*char : *jobrun);
ctl-opt thread(*concurrent);
/if defined(*crtbndrpg)
ctl-opt usrprf(*owner);
ctl-opt dftactgrp(*no);
ctl-opt actgrp(*caller);
/endif

216 IBM i: Performance and Query Optimization


dcl-ds QQQ_QRYSV_QRYS0100_t qualified template;
Header_Size uns(10);
Format_Name char(8); // QRYS0100 - Query Supervisor
Job_Name char(10); // Name of the job running the query
Job_User char(10); // User profile used to initiate job
Job_Number char(6); // Number of the job running the query
Subsystem char(10); // Subsystem in which the job is running
User_Name char(10); // The effective user name of the
// thread that reached the threshold
Query_Identifier char(8); // Uniquely identifies the query text
// and its environment (QRO hash)
Plan_Identifier uns(20); // Uniquely identifies the access plan
// implementing the query.
Threshold_Name ucs2(30) ccsid(1200); // User-defined name for threshold that
// was reached (in CCSID 1200)
Threshold_Type char(30); // Type of threshold reached
Threshold_Consumption_Value int(20); // Actual value reached by the
// query. Units vary with
// Threshold_Type.
Operation_Type int(5); // Type of query operation
Offset_to_SQL_Statement int(10); // 0, if not available
Length_of_SQL_Statement int(10); // 0, if not available
Offset_to_Host_Variable_List int(10); // 0, if no variables
Length_of_Host_Variable_List int(10); // 0, if no variables
Offset_to_CLIENT_ACCTNG int(10); // 0, if not defined
Length_of_CLIENT_ACCTNG int(10); // 0, if not defined
Offset_to_CLIENT_APPLNAME int(10); // 0, if not defined
Length_of_CLIENT_APPLNAME int(10); // 0, if not defined
Offset_to_CLIENT_PROGRAMID int(10); // 0, if not defined
Length_of_CLIENT_PROGRAMID int(10); // 0, if not defined
Offset_to_CLIENT_USERID int(10); // 0, if not defined
Length_of_CLIENT_USERID int(10); // 0, if not defined
Offset_to_CLIENT_WRKSTNNAME int(10); // 0, if not defined
Length_of_CLIENT_WRKSTNNAME int(10); // 0, if not defined
// char SQL_Statement_Text; /* Varying length, CCSID 1200 */
// char Host_Variable_List; /* Varying length, CCSID 1200 */
// char CLIENT_ACCTNG; /* Varying length */
// char CLIENT_APPLNAME; /* Varying length */
// char CLIENT_PROGRAMID; /* Varying length */
// char CLIENT_USERID; /* Varying length */
// char CLIENT_WRKSTNNAME; /* Varying length */
end-ds;

dcl-proc QS_sendmsg; // Main procedure


dcl-pi *n;
input likeds(QQQ_QRYSV_QRYS0100_t);
rc int(10);
end-pi;

dcl-pr qcmdexc extpgm;


cmd char(1000) const;
cmdlen packed(15:5) const;
end-pr;

dcl-s cmdstr char(1000);


dcl-s msg varchar(500);

//************************************************************************
// Init the return code to continue running the query
//************************************************************************
rc = 0;

msg = 'QUERY SUPERVISOR THRESHOLD ' + %trimr(input.Threshold_Name) +


' REACHED IN JOB ' + input.Job_Number + '/' +
%trimr(input.Job_User) + '/' + input.Job_Name ;

cmdstr =
'SBMJOB CMD(RUNSQL SQL(''call qsys2.send_message(''''SQL7064'''', '
+ %char(%len(msg)) + ' ,'''''+ msg + ''''')''))';

qcmdexc (cmdstr : %size(cmdstr));

return;
end-proc;

Database performance and query optimization 217


C exit program to send message to QSYSOPR
This Query Supervisor exit program sends an informational message to the QSYSOPR message queue.
To compile this C program, use the following commands. By using USRPRF(*OWNER), *PUBLIC does not
need to be given access to the objects used by this program. The owning profile of the created program
must have authority to the commands and objects used by the exit program.

CRTCMOD MODULE(SUPERVISOR/SND_QS_MSG) SRCFILE(SUPERVISOR/QCSRC)

CRTPGM PGM(SUPERVISOR/SND_QS_MSG) USRPRF(*OWNER) ACTGRP(*CALLER)

The program can be registered as an exit program using this command:

ADDEXITPGM EXITPNT(QIBM_QQQ_QRY_SUPER) FORMAT(QRYS0100) PGMNBR(*LOW) PGM(SUPERVISOR/SND_QS_MSG)


THDSAFE(*YES) TEXT('Query Supervisor send QSYSOPR message')

#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <iconv.h>
#include <stdio.h>
#include <eqqqrysv.h>

static void convertThresholdNameToJobCCSID(const char* input, char* output)


{
iconv_t converter;
char from_code[32], to_code[32];
size_t input_bytes, output_bytes;
int iconv_rc;

memset(from_code, 0, sizeof(from_code));
memset(to_code, 0, sizeof(to_code));
memcpy(from_code, "IBMCCSID012000000000", 20);
memcpy(to_code, "IBMCCSID00000", 13);
converter = iconv_open(to_code, from_code);

if (converter.return_value == 0) {
input_bytes = 60;
output_bytes = 30;
iconv_rc = iconv(converter,
&input, &input_bytes,
&output, &output_bytes);
iconv_close(converter);

if (iconv_rc >= 0)
return; /* Conversion was successful. */
}

sprintf(output, "iconv_open() failed with: %d", converter.return_value);


}

int trimmed_length(const char* str, int len)


{
const char* first_blank = memchr(str, ' ', len);
if (first_blank)
return first_blank - str;

return len;
}

/************************************************************************/
int main(int argc, char* argv[])
{
char length_string[10];
char cmd[600];
char thresholdNameInJobCCSID[30];
char msg[512];

const QQQ_QRYSV_QRYS0100_t* input = (QQQ_QRYSV_QRYS0100_t*)argv[1];


int* rc = (int*)argv[2];

*rc = 0; /* don't terminate the query */

memset(thresholdNameInJobCCSID, 0, sizeof(thresholdNameInJobCCSID));
convertThresholdNameToJobCCSID(input->Threshold_Name,

218 IBM i: Performance and Query Optimization


thresholdNameInJobCCSID);

memset(msg, 0, sizeof(msg));
strcat(msg,"QUERY SUPERVISOR THRESHOLD ");
strncat(msg, thresholdNameInJobCCSID, 30);
strcat(msg," REACHED IN JOB ");
strncat(msg, input->Job_Number, trimmed_length(input->Job_Number,6));
strcat(msg, "/");
strncat(msg, input->Job_User, trimmed_length(input->Job_User,10));
strcat(msg, "/");
strncat(msg, input->Job_Name, trimmed_length(input->Job_Name,10));

memset(length_string, 0, sizeof(length_string));
sprintf(length_string,"%d",strlen(msg));

/************************************************************************/
/* Use the SQL service send_message to send the message to QSYSOPR. */
/* SQL cannot be run within the exit program, so submit to batch. */
/************************************************************************/
memset(cmd, 0, sizeof(cmd));
strcat(cmd, "SBMJOB CMD(RUNSQL SQL('call qsys2.send_message(''SQL7064'',");
strcat(cmd,length_string);
strcat(cmd,",''");
strcat(cmd, msg);
strcat(cmd, "'')'))");
system(cmd);
}

CL exit program to send message to QSYSOPR


This Query Supervisor exit program sends an informational message to the QSYSOPR message queue.
To compile this ILE CL program, use the following command.

CRTBNDCL PGM(SUPERVISOR/QS_SENDMSG) SRCFILE(SUPERVISOR/QCLSRC) DFTACTGRP(*NO) ACTGRP(*CALLER)


USRPRF(*OWNER)

The program can be registered as an exit program using this command:

ADDEXITPGM EXITPNT(QIBM_QQQ_QRY_SUPER) FORMAT(QRYS0100) PGMNBR(*LOW) PGM(SUPERVISOR/QS_SENDMSG)


THDSAFE(*YES) TEXT('Query Supervisor send message to QSYSOPR')

By using USRPRF(*OWNER), *PUBLIC does not need to be given access to the objects used by this
program. The owning profile of the created program must have authority to the commands and objects
used by the exit program. The program will run in the activation group of the caller.

PGM PARM(&QRYS0100 &RC)


DCL VAR(&QRYS0100) TYPE(*CHAR) LEN(8192)
DCL VAR(&RC) TYPE(*INT) LEN(4)
DCL VAR(&MSGLEN) TYPE(*INT) LEN(2)
DCL VAR(&MSGTXT) TYPE(*CHAR) LEN(1022)
DCL VAR(&MSGDTA) TYPE(*CHAR) LEN(1024)
DCL VAR(&BINLOW) TYPE(*UINT) LEN(4)
DCL VAR(&BINHIGH) TYPE(*INT) LEN(4)
DCL VAR(&MAXINT) TYPE(*DEC) LEN(15 0) +
VALUE(4294967296)
DCL VAR(&JOBNAME) TYPE(*CHAR) LEN(10)
DCL VAR(&JOBUSER) TYPE(*CHAR) LEN(10)
DCL VAR(&JOBNBR) TYPE(*CHAR) LEN(6)
DCL VAR(&THRESHTYPE) TYPE(*CHAR) LEN(30)
DCL VAR(&THRESHVAL) TYPE(*DEC) LEN(15 0)

MONMSG MSGID(CPF0000)
/* INIT RETURN CODE TO CONTINUE RUNNING QUERY */
CHGVAR VAR(&RC) VALUE(0)

/* GET VALUES FROM THE INPUT FORMAT */


CHGVAR VAR(&JOBNAME) VALUE(%SST(&QRYS0100 13 10))
CHGVAR VAR(&JOBUSER) VALUE(%SST(&QRYS0100 23 10))
CHGVAR VAR(&JOBNBR) VALUE(%SST(&QRYS0100 33 6))
CHGVAR VAR(&THRESHTYPE) VALUE(%SST(&QRYS0100 135 30))
CHGVAR VAR(&BINHIGH) VALUE(%BINARY(&QRYS0100 165 4))
CHGVAR VAR(&BINLOW) VALUE(%BINARY(&QRYS0100 169 4))
CHGVAR VAR(&THRESHVAL) VALUE(%DEC(&BINHIGH 15 0) * +
&MAXINT + %DEC(&BINLOW 15 0))

/* GENERATE MESSAGE TEXT STRING */

Database performance and query optimization 219


CHGVAR VAR(&MSGTXT) VALUE('QUERY SUPERVISOR +
THRESHOLD TYPE ' *BCAT &THRESHTYPE *TCAT +
', THRESHOLD VALUE ' *BCAT +
%CHAR(&THRESHVAL) *BCAT 'REACHED IN JOB ' +
*BCAT &JOBNBR *TCAT '/' *TCAT &JOBUSER +
*TCAT '/' *TCAT &JOBNAME )
CHGVAR VAR(&MSGLEN) VALUE(%LEN(&MSGTXT))
CHGVAR VAR(%BINARY(&MSGDTA 1 2)) VALUE(&MSGLEN)
CHGVAR VAR(&MSGDTA) VALUE(&MSGDTA *TCAT &MSGTXT)
SNDPGMMSG MSGID(SQL7064) MSGF(QSQLMSG) MSGDTA(&MSGDTA) +
TOMSGQ(*SYSOPR)

ENDPGM

Exit program to end query


This Query Supervisor exit program shows how to request that the query that was running when the
threshold was reached is to be stopped.
When this exit program is called, it instructs the Query Supervisor to end the query if it is called for either:
1. An ELAPSED TIME threshold when the threshold consumption has reached at least 60 minutes
2. A threshold with a name that starts with the letters TERMINATE
The threshold definitions used by the C and ILE RPG sample programs are:

CALL QSYS2.ADD_QUERY_THRESHOLD(THRESHOLD_NAME=>'One hour limit',


THRESHOLD_TYPE=>'ELAPSED TIME',
THRESHOLD_VALUE=>'3600');
CALL QSYS2.ADD_QUERY_THRESHOLD(THRESHOLD_NAME=>'TERMINATE FOR STORAGE',
THRESHOLD_TYPE=>'TEMPORARY STORAGE',
THRESHOLD_VALUE=>'500');

ILE RPG exit program to end query


This Query Supervisor exit program shows how to request that the query should be ended.
To compile this ILE RPG program, use the following command.

CRTBNDRPG PGM(SUPERVISOR/QS_ENDQRY) SRCFILE(SUPERVISOR/QRPGLESRC)

If CRTRPGMOD and CRTPGM are used to compile and build the program, be sure to include
USRPRF(*OWNER) and ACTGRP(*CALLER) on the CRTPGM command.
The program can be registered as an exit program using this command:

ADDEXITPGM EXITPNT(QIBM_QQQ_QRY_SUPER) FORMAT(QRYS0100) PGMNBR(*LOW) PGM(SUPERVISOR/QS_ENDQRY)


THDSAFE(*YES) TEXT('End query after 60 minutes or TERMINATE threshold')

By including the THREAD, USRPRF, DFTACTGRP, and ACTGRP options in the source, they can be omitted
on the compiler command. By using USRPRF(*OWNER), *PUBLIC does not need to be given access to
the objects used by this program. The owning profile of the created program must have authority to the
commands and objects used by the exit program. The program uses THREAD(*CONCURRENT) to ensure
thread safety. The program will run in the activation group of the caller.

**free
ctl-opt main(QS_endqry);
ctl-opt ccsid(*char : *jobrun);
ctl-opt thread(*concurrent);
/if defined(*crtbndrpg)
ctl-opt usrprf(*owner);
ctl-opt dftactgrp(*no);
ctl-opt actgrp(*caller);
/endif

dcl-ds QQQ_QRYSV_QRYS0100_t qualified template;


Header_Size uns(10);
Format_Name char(8); // QRYS0100 - Query Supervisor
Job_Name char(10); // Name of the job running the query
Job_User char(10); // User profile used to initiate job
Job_Number char(6); // Number of the job running the query

220 IBM i: Performance and Query Optimization


Subsystem char(10); // Subsystem in which the job is running
User_Name char(10); // The effective user name of the
// thread that reached the threshold
Query_Identifier char(8); // Uniquely identifies the query text
// and its environment (QRO hash)
Plan_Identifier uns(20); // Uniquely identifies the access plan
// implementing the query.
Threshold_Name ucs2(30) ccsid(1200); // User-defined name for threshold that
// was reached (in CCSID 1200)
Threshold_Type char(30); // Type of threshold reached
Threshold_Consumption_Value int(20); // Actual value reached by the
// query. Units vary with
// Threshold_Type.
Operation_Type int(5); // Type of query operation
Offset_to_SQL_Statement int(10); // 0, if not available
Length_of_SQL_Statement int(10); // 0, if not available
Offset_to_Host_Variable_List int(10); // 0, if no variables
Length_of_Host_Variable_List int(10); // 0, if no variables
Offset_to_CLIENT_ACCTNG int(10); // 0, if not defined
Length_of_CLIENT_ACCTNG int(10); // 0, if not defined
Offset_to_CLIENT_APPLNAME int(10); // 0, if not defined
Length_of_CLIENT_APPLNAME int(10); // 0, if not defined
Offset_to_CLIENT_PROGRAMID int(10); // 0, if not defined
Length_of_CLIENT_PROGRAMID int(10); // 0, if not defined
Offset_to_CLIENT_USERID int(10); // 0, if not defined
Length_of_CLIENT_USERID int(10); // 0, if not defined
Offset_to_CLIENT_WRKSTNNAME int(10); // 0, if not defined
Length_of_CLIENT_WRKSTNNAME int(10); // 0, if not defined
// char SQL_Statement_Text; /* Varying length, CCSID 1200 */
// char Host_Variable_List; /* Varying length, CCSID 1200 */
// char CLIENT_ACCTNG; /* Varying length */
// char CLIENT_APPLNAME; /* Varying length */
// char CLIENT_PROGRAMID; /* Varying length */
// char CLIENT_USERID; /* Varying length */
// char CLIENT_WRKSTNNAME; /* Varying length */
end-ds;

dcl-proc QS_endqry; // Main procedure


dcl-pi *n;
input likeds(QQQ_QRYSV_QRYS0100_t);
rc int(10);
end-pi;

//************************************************************************
// Init the return code to continue running the query
//************************************************************************
rc = 0;

//* Have we reached an ELAPSED TIME threshold running for 60 minutes? */


if input.Threshold_Type = 'ELAPSED TIME'
and input.Threshold_Consumption_Value >= 60 * 60;
rc = 1; //* Terminate the query */
endif;

//* Have we reached a threshold named TERMINATE...? */


if %subst(input.Threshold_Name:1:%len('TERMINATE')) = 'TERMINATE';
rc = 1;
endif;
return;
end-proc;

C exit program to end query


This Query Supervisor exit program shows how to request that the query should be ended.
To compile this C program, use the following commands:

CRTCMOD MODULE(SUPERVISOR/END_QUERY) SRCFILE(SUPERVISOR/QCSRC) LOCALETYPE(*LOCALEUCS2)

CRTPGM PGM(SUPERVISOR/END_QUERY) USRPRF(*OWNER) ACTGRP(*CALLER)

The program can be registered as an exit program using this command:

ADDEXITPGM EXITPNT(QIBM_QQQ_QRY_SUPER) FORMAT(QRYS0100) PGMNBR(*LOW) PGM(SUPERVISOR/END_QUERY)


THDSAFE(*YES) TEXT('End query after 60 minutes or TERMINATE threshold')

#include <string.h>

Database performance and query optimization 221


#include <wchar.h>
#include <eqqqrysv.h>

/* Threshold names are given in CCSID_1200 */


const wchar_t TERMINATE_STRING_1200[] = L"TERMINATE";

int main(int argc, char* argv[])


{
const QQQ_QRYSV_QRYS0100_t* input = (QQQ_QRYSV_QRYS0100_t*)argv[1];
int* rc = (int*)argv[2];

*rc = 0; /* Default action is to allow query to continue running */

/* Have we reached a threshold detecting that the query has been


running for 60 minutes or more? */
if (memcmp(input->Threshold_Type, "ELAPSED TIME", 12) == 0 &&
input->Threshold_Consumption_Value >= 60 * 60)
*rc = 1; /* Terminate the query */

/* Have we reached a threshold named TERMINATE...? */


if (memcmp(input->Threshold_Name,
TERMINATE_STRING_1200,
sizeof(TERMINATE_STRING_1200)-2) == 0)
*rc = 1;

return 0;
}

CL exit program to end query


This Query Supervisor exit program shows how to request that the query should be ended.
To compile this ILE CL program, use the following command.

CRTBNDCL PGM(SUPERVISOR/QS_ENDQRY) SRCFILE(SUPERVISOR/QCLSRC) DFTACTGRP(*NO) ACTGRP(*CALLER)


USRPRF(*OWNER)

The program can be registered as an exit program using this command:

ADDEXITPGM EXITPNT(QIBM_QQQ_QRY_SUPER) FORMAT(QRYS0100) PGMNBR(*LOW) PGM(SUPERVISOR/QS_ENDQRY)


THDSAFE(*YES) TEXT('End query after 60 minutes or TERMINATE threshold')

By using USRPRF(*OWNER), *PUBLIC does not need to be given access to the objects used by this
program. The owning profile of the created program must have authority to the commands and objects
used by the exit program. The program will run in the activation group of the caller.

PGM PARM(&QRYS0100 &RC)


DCL VAR(&QRYS0100) TYPE(*CHAR) LEN(8192)
DCL VAR(&RC) TYPE(*INT) LEN(4)
DCL VAR(&BINLOW) TYPE(*UINT) LEN(4)
DCL VAR(&BINHIGH) TYPE(*INT) LEN(4)
DCL VAR(&MAXINT) TYPE(*DEC) LEN(15 0) +
VALUE(4294967296)
DCL VAR(&THRESHNAME) TYPE(*CHAR) LEN(60)
DCL VAR(&THRESHTYPE) TYPE(*CHAR) LEN(30)
DCL VAR(&THRESHVAL) TYPE(*DEC) LEN(15 0)
DCL VAR(&TERMINATE) TYPE(*CHAR) LEN(18)
DCL VAR(&ONEHOUR) TYPE(*INT) LEN(4)

MONMSG MSGID(CPF0000)
/* INIT RETURN CODE TO CONTINUE RUNNING QUERY */
CHGVAR VAR(&RC) VALUE(0)
/* SET UNICODE HEX VALUE FOR THE THRESHOLD NAMED "TERMINATE" */
CHGVAR VAR(&TERMINATE) +
VALUE(X'005400450052004D0049004E004100540045')
/* VALUE FOR ONE HOUR OF ELAPSED TIME */
CHGVAR VAR(&ONEHOUR) VALUE(60 * 60)

/* GET VALUES FROM THE INPUT FORMAT */


CHGVAR VAR(&THRESHNAME) VALUE(%SST(&QRYS0100 75 60))
CHGVAR VAR(&THRESHTYPE) VALUE(%SST(&QRYS0100 135 30))
CHGVAR VAR(&BINHIGH) VALUE(%BINARY(&QRYS0100 165 4))
CHGVAR VAR(&BINLOW) VALUE(%BINARY(&QRYS0100 169 4))
CHGVAR VAR(&THRESHVAL) VALUE(%DEC(&BINHIGH 15 0) * +
&MAXINT + %DEC(&BINLOW 15 0))

/* DECIDE WHETHER QUERY SHOULD BE ENDED */

222 IBM i: Performance and Query Optimization


IF COND((&THRESHTYPE = 'ELAPSED TIME') *AND +
(&THRESHVAL *GE &ONEHOUR)) +
THEN(CHGVAR VAR(&RC) VALUE(1))
IF COND(%SST(&THRESHNAME 1 18) *EQ &TERMINATE) +
THEN(CHGVAR VAR(&RC) VALUE(1))

ENDPGM

Exit program to dump plan cache information for query


This Query Supervisor exit program dumps plan cache information about the query that reached a
threshold.
The information is placed in a table named SUPERVISOR.PLAN_DUMPS. If the table does not exist, it will
be created. If the table exists, the new plan cache snapshot will be appended to it. The SUPERVISOR
schema must exist. See “DUMP_PLAN_CACHE procedure” on page 357 for details.
Because SQL cannot be used directly in the exit program, the Run SQL (RUNSQL) CL command is
submitted as a batch job.

ILE RPG exit program to dump plan cache information for query
This Query Supervisor exit program dumps plan cache information about the query that reached a
threshold.
To compile this ILE RPG program, use the following command. Before compiling, the sample source must
be modified as indicated by the comment in the code. The USER parameter on the SBMJOB command
must name a profile on the system that has the required authority to call QSYS2.DUMP_PLAN_CACHE().
This authority is *JOBCTL special authority or QIBM_DB_SQLADM function usage. In addition, the owner
of the QS_DMPQRY program must have *USE authority to the profile specified on the USER parameter.
One option is to make USER the same as the program owner.

CRTBNDRPG PGM(SUPERVISOR/QS_DMPQRY) SRCFILE(SUPERVISOR/QRPGLESRC)

If CRTRPGMOD and CRTPGM are used to compile and build the program, be sure to include
USRPRF(*OWNER) and ACTGRP(*CALLER) on the CRTPGM command.
The program can be registered as an exit program using this command:

ADDEXITPGM EXITPNT(QIBM_QQQ_QRY_SUPER) FORMAT(QRYS0100) PGMNBR(*LOW) PGM(SUPERVISOR/QS_DMPQRY)


THDSAFE(*YES) TEXT('Query supervisor dump plan cache')

By including the THREAD, USRPRF, DFTACTGRP, and ACTGRP options in the source, they can be omitted
on the compiler command. By using USRPRF(*OWNER), *PUBLIC does not need to be given access to
the objects used by this program. The owning profile of the created program must have authority to the
commands and objects used by the exit program. The program uses THREAD(*CONCURRENT) to ensure
thread safety. The program will run in the activation group of the caller.

**free
ctl-opt main(QS_dmpqry);
ctl-opt ccsid(*char : *jobrun);
ctl-opt thread(*concurrent);
/if defined(*crtbndrpg)
ctl-opt usrprf(*owner);
ctl-opt dftactgrp(*no);
ctl-opt actgrp(*caller);
/endif

dcl-ds QQQ_QRYSV_QRYS0100_t qualified template;


Header_Size uns(10);
Format_Name char(8); // QRYS0100 - Query Supervisor
Job_Name char(10); // Name of the job running the query
Job_User char(10); // User profile used to initiate job
Job_Number char(6); // Number of the job running the query
Subsystem char(10); // Subsystem in which the job is running
User_Name char(10); // The effective user name of the
// thread that reached the threshold
Query_Identifier char(8); // Uniquely identifies the query text
// and its environment (QRO hash)

Database performance and query optimization 223


Plan_Identifier uns(20); // Uniquely identifies the access plan
// implementing the query.
Threshold_Name ucs2(30) ccsid(1200); // User-defined name for threshold that
// was reached (in CCSID 1200)
Threshold_Type char(30); // Type of threshold reached
Threshold_Consumption_Value int(20); // Actual value reached by the
// query. Units vary with
// Threshold_Type.
Operation_Type int(5); // Type of query operation
Offset_to_SQL_Statement int(10); // 0, if not available
Length_of_SQL_Statement int(10); // 0, if not available
Offset_to_Host_Variable_List int(10); // 0, if no variables
Length_of_Host_Variable_List int(10); // 0, if no variables
Offset_to_CLIENT_ACCTNG int(10); // 0, if not defined
Length_of_CLIENT_ACCTNG int(10); // 0, if not defined
Offset_to_CLIENT_APPLNAME int(10); // 0, if not defined
Length_of_CLIENT_APPLNAME int(10); // 0, if not defined
Offset_to_CLIENT_PROGRAMID int(10); // 0, if not defined
Length_of_CLIENT_PROGRAMID int(10); // 0, if not defined
Offset_to_CLIENT_USERID int(10); // 0, if not defined
Length_of_CLIENT_USERID int(10); // 0, if not defined
Offset_to_CLIENT_WRKSTNNAME int(10); // 0, if not defined
Length_of_CLIENT_WRKSTNNAME int(10); // 0, if not defined
// char SQL_Statement_Text; /* Varying length, CCSID 1200 */
// char Host_Variable_List; /* Varying length, CCSID 1200 */
// char CLIENT_ACCTNG; /* Varying length */
// char CLIENT_APPLNAME; /* Varying length */
// char CLIENT_PROGRAMID; /* Varying length */
// char CLIENT_USERID; /* Varying length */
// char CLIENT_WRKSTNNAME; /* Varying length */
end-ds;

dcl-proc QS_dmpqry; // Main procedure


dcl-pi *n;
input likeds(QQQ_QRYSV_QRYS0100_t);
rc int(10);
end-pi;

dcl-pr qcmdexc extpgm;


cmd char(1000) const;
cmdlen packed(15:5) const;
end-pr;

dcl-s cmdstr char(1000);

//************************************************************************
// Init the return code to continue running the query
//************************************************************************
rc = 0;

cmdstr =
'SBMJOB CMD(RUNSQL SQL(''call qsys2.dump_plan_cache('
+ 'FILESCHEMA => ''''SUPERVISOR'''', FILENAME => ''''PLANDUMPS'''' '
+ ', PLAN_IDENTIFIER => '''''
+ %char(input.Plan_Identifier) + ''''')'')) '
+ 'USER('
+ 'MYAUTHUSER' // Replace MYAUTHUSER with a user profile authorized
// to DUMP_PLAN_CACHE().
+ ')';
qcmdexc (cmdstr : %size(cmdstr));

return;
end-proc;

C exit program to dump plan cache information for query


This Query Supervisor exit program dumps plan cache information about the query that reached a
threshold.
To compile this C program, use the following commands. By using USRPRF(*OWNER), *PUBLIC does
not need to be given access to the objects used by this program. The owning profile of the created
program must have authority to the commands and objects used by the exit program. The macro
definition for AUTHORIZED_USER should be customized, replacing MYAUTHUSER with a profile that has
the required authority to call QSYS2.DUMP_PLAN_CACHE(). This authority is *JOBCTL special authority or
QIBM_DB_SQLADM function usage. In addition, the owner of the DUMP_QUERY program must have *USE

224 IBM i: Performance and Query Optimization


authority to the profile identified by AUTHORIZED_USER. One option is to make AUTHORIZER_USER the
same as the program owner.

CRTCMOD MODULE(SUPERVISOR/DUMP_QUERY) SRCFILE(SUPERVISOR/QCSRC)


DEFINE('AUTHORIZED_USER="MYAUTHUSER"')

CRTPGM PGM(SUPERVISOR/DUMP_QUERY) USRPRF(*OWNER) ACTGRP(*CALLER)

The program can be registered as an exit program using this command:

ADDEXITPGM EXITPNT(QIBM_QQQ_QRY_SUPER) FORMAT(QRYS0100) PGMNBR(*LOW) PGM(SUPERVISOR/DUMP_QUERY)


THDSAFE(*YES) TEXT('Query Supervisor dump plan cache')

#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <eqqqrysv.h>

int main(int argc, char* argv[])


{
char plan_id_string[21];
char cmd[600];

const QQQ_QRYSV_QRYS0100_t* input = (QQQ_QRYSV_QRYS0100_t*)argv[1];


int* rc = (int*)argv[2];

*rc = 0; /* don't terminate the query */

/************************************************************************/
/* SQL cannot be run within the exit program, so submit to batch. */
/************************************************************************/
memset(cmd, 0, sizeof(cmd));
strcat(cmd, "SBMJOB CMD(RUNSQL SQL('call qsys2.dump_plan_cache(");
strcat(cmd, "FILESCHEMA => ''SUPERVISOR'', FILENAME => ''PLANDUMPS''");
strcat(cmd, ", PLAN_IDENTIFIER => ");
sprintf(plan_id_string, "%llu", input->Plan_Identifier);
strcat(cmd, plan_id_string);
strcat(cmd, ")')) USER(");
strcat(cmd, AUTHORIZED_USER);
strcat(cmd, ")");
system(cmd);
}

CL exit program to dump plan cache information for query


This Query Supervisor exit program dumps plan cache information about the query that reached a
threshold.
To compile this ILE CL program, use the following command. Before compiling, the sample source must
be modified as indicated by the comment in the code. The USER parameter on the SBMJOB command
must name a profile on the system that has the required authority to call QSYS2.DUMP_PLAN_CACHE().
This authority is *JOBCTL special authority or QIBM_DB_SQLADM function usage. In addition, the owner
of the QS_DMPQRY program must have *USE authority to the profile specified on the USER parameter.
One option is to make USER the same as the program owner.

CRTBNDCL PGM(SUPERVISOR/QS_DMPQRY) SRCFILE(SUPERVISOR/QCLSRC) DFTACTGRP(*NO) ACTGRP(*CALLER)


USRPRF(*OWNER)

The program can be registered as an exit program using this command:

ADDEXITPGM EXITPNT(QIBM_QQQ_QRY_SUPER) FORMAT(QRYS0100) PGMNBR(*LOW) PGM(SUPERVISOR/QS_DMPQRY)


THDSAFE(*YES) TEXT('Query supervisor dump plan cache')

By using USRPRF(*OWNER), *PUBLIC does not need to be given access to the objects used by this
program. The owning profile of the created program must have authority to the commands and objects
used by the exit program. The program will run in the activation group of the caller.

PGM PARM(&QRYS0100 &RC)


DCL VAR(&QRYS0100) TYPE(*CHAR) LEN(8192)

Database performance and query optimization 225


DCL VAR(&RC) TYPE(*INT) LEN(4)
DCL VAR(&BINLOW) TYPE(*UINT) LEN(4)
DCL VAR(&BINHIGHU) TYPE(*UINT) LEN(4)
DCL VAR(&MAXINT) TYPE(*DEC) LEN(15 0) +
VALUE(4294967296)
DCL VAR(&PLANID) TYPE(*DEC) LEN(15 0)

MONMSG MSGID(CPF0000)
/* INIT RETURN CODE TO CONTINUE RUNNING QUERY */
CHGVAR VAR(&RC) VALUE(0)

/* GET VALUES FROM THE INPUT FORMAT */


CHGVAR VAR(&BINHIGHU) VALUE(%BINARY(&QRYS0100 67 4))
CHGVAR VAR(&BINLOW) VALUE(%BINARY(&QRYS0100 71 4))
CHGVAR VAR(&PLANID) VALUE(%DEC(&BINHIGHU 15 0) * +
&MAXINT + %DEC(&BINLOW 15 0))

/* SUBMIT JOB TO DUMP THE PLAN CACHE FOR THIS QUERY */


SBMJOB CMD(RUNSQL SQL('CALL QSYS2.DUMP_PLAN_CACHE(' +
*BCAT 'FILESCHEMA => ''SUPERVISOR'', +
FILENAME => ''PLANDUMPS'', +
PLAN_IDENTIFIER=> ''' *TCAT +
%CHAR(&PLANID) *TCAT ''')')) +
USER(MYAUTHUSER)
/* Replace MYAUTHUSER with a user profile */
/* authorized to DUMP_PLAN_CACHE().
*/
ENDPGM

Exit program to log information using a data queue


This Query Supervisor exit program shows how to use an asynchronous job to log information about the
query that reported a threshold.
This example is more complicated. It illustrates how a lightweight exit program can offload processing to
a background job for more complex consumption. By doing this, the exit program can complete quicker,
causing less of a disruption to the query that caused the threshold to be reported. The example has three
pieces.
1. Configuration details
2. An exit program (written in ILE RPG or C)
3. An SQL procedure that performs the actual logging
The exit program produces a JSON object encoded in UTF-16 that contains all of the threshold
information sent to the exit program. It sends this JSON object to a data queue named SUPERVISOR/
SUPER_DQ. An SQL procedure running in a separate job consumes JSON objects from the data queue. In
this example, the procedure logs the entry to a log table.

Setup configuration
There are several objects that need to be defined for this data queue processing solution.
The following table is used to log the Query Supervisor data received from the SEND_JSON exit program.
It is populated by the process_QS_data_queue() procedure defined later.

create schema SQE_QUERY_SUPERVISOR for schema SUPERVISOR ;

create table SQE_QUERY_SUPERVISOR.SUPERVISOR_LOG for system name SUPERLOG (


THRESHOLD_TIMESTAMP for column WHENHIT timestamp,
JOB_NAME varchar(10) default null,
JOB_USER varchar(10) default null,
JOB_NUMBER for column JOBNUM varchar(6) default null,
SUBSYSTEM varchar(10) default null,
USER_NAME varchar(10) default null,
THRESHOLD_NAME for column THRESHNAME varchar(30) ccsid 1208 default null,
THRESHOLD_TYPE for column THRESHTYPE varchar(30) ccsid 1208 default null,
THRESHOLD_CONSUMPTION_VALUE for column THRESHVAL bigint default null,
OPERATION_TYPE for column OP smallint default null,
SQL_STATEMENT_TEXT for column STMTTEXT varchar(10000) ccsid 1208 default null,
HOST_VARIABLE_LIST for column HVLIST varchar(10000) ccsid 1208 default null,
CLIENT_ACCTNG for column "ACCTNG" varchar(255) ccsid 1208 default null,
CLIENT_APPLNAME for column "APPLNAME" varchar(255) ccsid 1208 default null,
CLIENT_PROGRAMID for column "PROGRAMID" varchar(255) ccsid 1208 default null,

226 IBM i: Performance and Query Optimization


CLIENT_USERID for column "USERID" varchar(255) ccsid 1208 default null,
CLIENT_WRKSTNNAME for column "WRKSTNNAME" varchar(255) ccsid 1208 default null,
QUERY_IDENTIFIER for column QRO_HASH varchar(8) ccsid 1208 default null,
QUERY_PLAN_IDENTIFIER for column plan_id decimal(20,0) default null);

The following data queue is the communication mechanism used by the exit program that got control
because of a Query Supervisor threshold having been met or exceeded. The detail passed in the data
queue is a JSON document where each key name is a piece of data passed to the Query Supervisor exit
program.

cl:CRTDTAQ DTAQ(SUPERVISOR/SUPER_DQ) MAXLEN(45000) FORCE(*YES) SIZE(*MAX2GB 1000)


AUTORCL(*YES) TEXT('Query Supervisor Threshold Processor');

Once the programs are in place, a job must be started to run the asynchronous SQL procedure. It will sit
and wait for data queue entries to process.
This command can be added to the QSTRUP processing to allow it to be automatically restarted upon
system IPL

cl:SBMJOB CMD(RUNSQL SQL('call supervisor.process_QS_data_queue()') COMMIT(*NONE))


JOB(SUPERMGR)
INLASPGRP(*NONE) LOG(4 00 *SECLVL) JOBMSGQFL(*PRTWRAP) CCSID(37);

ILE RPG exit program to log information using a data queue


This Query Supervisor exit program shows how to use an asynchronous job to log information about the
query that reported a threshold.
To compile this ILE RPG program, use the following command.

CRTBNDRPG PGM(SUPERVISOR/QS_DTAQ) SRCFILE(SUPERVISOR/QRPGLESRC)

If CRTRPGMOD and CRTPGM are used to compile and build the program, be sure to include
USRPRF(*OWNER) and ACTGRP(*CALLER) on the CRTPGM command.
The program can be registered as an exit program using this command:

ADDEXITPGM EXITPNT(QIBM_QQQ_QRY_SUPER) FORMAT(QRYS0100) PGMNBR(*LOW) PGM(SUPERVISOR/QS_DTAQ)


THDSAFE(*YES) TEXT('Query Supervisor logging with data queue')

By including the THREAD, USRPRF, DFTACTGRP, and ACTGRP options in the source, they can be omitted
on the compiler command. By using USRPRF(*OWNER), *PUBLIC does not need to be given access to
the objects used by this program. The owning profile of the created program must have authority to the
commands and objects used by the exit program. The program uses THREAD(*CONCURRENT) to ensure
thread safety. The program will run in the activation group of the caller.

**free
ctl-opt main(QS_dtaq);
ctl-opt ccsid(*char : *jobrun);
ctl-opt thread(*concurrent);
/if defined(*crtbndrpg)
ctl-opt usrprf(*owner);
ctl-opt dftactgrp(*no);
ctl-opt actgrp(*caller);
/endif

dcl-ds QQQ_QRYSV_QRYS0100_t qualified template;


Header_Size uns(10);
Format_Name char(8); // QRYS0100 - Query Supervisor
Job_Name char(10); // Name of the job running the query
Job_User char(10); // User profile used to initiate job
Job_Number char(6); // Number of the job running the query
Subsystem char(10); // Subsystem in which the job is running
User_Name char(10); // The effective user name of the
// thread that reached the threshold
Query_Identifier char(8); // Uniquely identifies the query text
// and its environment (QRO hash)
Plan_Identifier uns(20); // Uniquely identifies the access plan
// implementing the query.
Threshold_Name ucs2(30) ccsid(1200); // User-defined name for threshold that

Database performance and query optimization 227


// was reached (in CCSID 1200)
Threshold_Type char(30); // Type of threshold reached
Threshold_Consumption_Value int(20); // Actual value reached by the
// query. Units vary with
// Threshold_Type.
Operation_Type int(5); // Type of query operation
Offset_to_SQL_Statement int(10); // 0, if not available
Length_of_SQL_Statement int(10); // 0, if not available
Offset_to_Host_Variable_List int(10); // 0, if no variables
Length_of_Host_Variable_List int(10); // 0, if no variables
Offset_to_CLIENT_ACCTNG int(10); // 0, if not defined
Length_of_CLIENT_ACCTNG int(10); // 0, if not defined
Offset_to_CLIENT_APPLNAME int(10); // 0, if not defined
Length_of_CLIENT_APPLNAME int(10); // 0, if not defined
Offset_to_CLIENT_PROGRAMID int(10); // 0, if not defined
Length_of_CLIENT_PROGRAMID int(10); // 0, if not defined
Offset_to_CLIENT_USERID int(10); // 0, if not defined
Length_of_CLIENT_USERID int(10); // 0, if not defined
Offset_to_CLIENT_WRKSTNNAME int(10); // 0, if not defined
Length_of_CLIENT_WRKSTNNAME int(10); // 0, if not defined
// char SQL_Statement_Text; /* Varying length, CCSID 1200 */
// char Host_Variable_List; /* Varying length, CCSID 1200 */
// char CLIENT_ACCTNG; /* Varying length */
// char CLIENT_APPLNAME; /* Varying length */
// char CLIENT_PROGRAMID; /* Varying length */
// char CLIENT_USERID; /* Varying length */
// char CLIENT_WRKSTNNAME; /* Varying length */
end-ds;

// Properties of the data queue that we will send the JSON to:
dcl-c DataQLib 'SUPERVISOR';
dcl-c DataQName 'SUPER_DQ';
dcl-c DataQMaxBytes 45000;

dcl-pr QSNDDTAQ extpgm;


DataQName char(10) const;
DataQLib char(10) const;
len packed(5) const;
data char(DataQMaxBytes) options(*varsize);
end-pr;

dcl-c MAX_SOURCE_LEN 11000;


dcl-c MAX_TARGET_LEN 22500;

// - Define a lookup table that indicates how to handle escapable JSON


// characters. Each entry represents one of the first 160 UTF-16
// codepoints.
// - The array JsonEscapeAction is initialized in subroutine
// initEscapeAction
dcl-c None 0;
dcl-c UTF16 1;
dcl-c Backspace 2;
dcl-c Tab 3;
dcl-c Newline 4;
dcl-c Formfeed 5;
dcl-c CR 6;
dcl-c Quote 7;
dcl-c Backslash 8;

dcl-s JsonEscapeAction int(10) dim(160);

// Defines properties for the buffer containing the JSON payload.


dcl-ds BufferInfo_t qualified;
baseptr pointer;
curptr pointer;
allocsize int(10);
truncated ind;
end-ds;

// Define constants used for generating JSON escape sequences.


dcl-c HexChars %ucs2('0123456789ABCDEF');
dcl-c EscapeChars %ucs2(' btnfr"\'); // "
dcl-c UnicodePrefix %ucs2('u00');

dcl-pr Qp0zLprintf extproc(*dclcase);


template pointer value options(*string);
parm pointer value options(*string : *nopass);
end-pr;
dcl-c NEWLINE_CH
x'15';

228 IBM i: Performance and Query Optimization


// SEND_JSON: main
procedure
// SEND_JSON:
main procedure
dcl-proc send_json;

dcl-pi *n;
input likeds(QQQ_QRYSV_QRYS0100_t);
rc int(10);
end-pi;

dcl-s based_char char(MAX_SOURCE_LEN) based(based_char_ptr);


dcl-s based_ucs2 ucs2(MAX_SOURCE_LEN) based(based_ucs2_ptr);
dcl-s based_buf_data char(1) based(buf.baseptr);
dcl-s debug_based_buf_data_ucs2 ucs2(MAX_TARGET_LEN) based(buf.baseptr);
dcl-s ts timestamp(0);
dcl-s pInput pointer;

dcl-ds buf
likeds(BufferInfo_t);

// Don't terminate the query


rc = 0;

// Initialization
pInput = %addr(input);
exsr initEscapeAction;

// Set up the buffer used for the final JSON payload.


buf.baseptr = %alloc (DataQMaxBytes);
buf.allocsize = DataQMaxBytes;
buf.curptr = buf.baseptr;
buf.truncated = *off;

// JSON encoding starts here.


json_append(buf :'{');

// Insert fixed length fields from the input.


// All fields must be converted into UTF-16 strings, except
// for the threshold name, which is already UTF-16.

json_key(buf : 'threshold_timestamp');
ts = %timestamp();
json_append(buf : '"'
+ %char(%date(ts))
+ ' '
+ %char(%time(ts) : *hms)
+ '"');

json_append(buf : ',');
json_key(buf : 'job_name');
json_string_value(buf : %trimr(input.Job_Name));

json_append(buf : ',');
json_key(buf : 'job_user');
json_string_value(buf : %trimr(input.Job_User));

json_append(buf : ',');
json_key(buf : 'job_number');
json_string_value(buf : input.Job_Number);

json_append(buf : ',');
json_key(buf : 'subsystem');
json_string_value(buf : %trimr(input.Subsystem));

json_append(buf : ',');
json_key(buf : 'user_name');
json_string_value(buf : %trimr(input.User_Name));

json_append(buf : ',');
json_key(buf : 'query_identifier');
json_string_value(buf : input.Query_Identifier);

json_append(buf : ',');
json_key(buf : 'query_plan_identifier');
json_numeric_value(buf : input.Plan_Identifier);

json_append(buf : ',');
json_key(buf : 'threshold_name');
json_escape_value(buf : %trimr(input.Threshold_Name));

Database performance and query optimization 229


json_append(buf : ',');
json_key(buf : 'threshold_type');
json_string_value(buf : %trimr(input.Threshold_Type));

json_append(buf : ',');
json_key(buf : 'threshold_consumption_value');
json_numeric_value(buf : input.Threshold_Consumption_Value);

json_append(buf : ',');
json_key(buf : 'operation_type');
json_numeric_value(buf : input.Operation_Type);

// Insert variable length fields.


// Client special registers need to be translated to UTF-16
// before they can be escaped and inserted.
// The SQL statement text and the host variable list can be
// copied over (with JSON escaping) as they are, since they
// are passed in as UTF-16 data.

if input.Length_of_CLIENT_ACCTNG > 0;
json_append(buf : ',');
json_key(buf : 'client_acctng');
based_char_ptr = pInput + input.Offset_to_CLIENT_ACCTNG;
json_escape_value(buf
: %subst(based_char : 1
: Input.Length_of_CLIENT_ACCTNG));
endif;

if input.Length_of_CLIENT_APPLNAME > 0;
json_append(buf : ',');
json_key(buf : 'client_applname');
based_char_ptr = pInput + input.Offset_to_CLIENT_APPLNAME;
json_escape_value(buf
: %subst(based_char : 1
: Input.Length_of_CLIENT_APPLNAME));
endif;

if input.Length_of_CLIENT_PROGRAMID > 0;
json_append(buf : ',');
json_key(buf : 'client_programid');
based_char_ptr = pInput + input.Offset_to_CLIENT_PROGRAMID;
json_escape_value(buf
: %subst(based_char : 1
: Input.Length_of_CLIENT_PROGRAMID));
endif;

if input.Length_of_CLIENT_USERID > 0;
json_append(buf : ',');
json_key(buf : 'client_userid');
based_char_ptr = pInput + input.Offset_to_CLIENT_USERID;
json_escape_value(buf
: %subst(based_char : 1
: Input.Length_of_CLIENT_USERID));
endif;

if input.Length_of_CLIENT_WRKSTNNAME > 0;
json_append(buf : ',');
json_key(buf : 'client_wrkstnname');
based_char_ptr = pInput + input.Offset_to_CLIENT_WRKSTNNAME;
json_escape_value(buf
: %subst(based_char : 1
: Input.Length_of_CLIENT_WRKSTNNAME));
endif;

if input.Length_of_SQL_Statement > 0;
json_append(buf : ',');
json_key(buf : 'sql_statement_text');
based_ucs2_ptr = pInput + input.Offset_to_SQL_Statement;
json_escape_value(buf
: %subst(based_ucs2 : 1
: %div(Input.Length_of_SQL_Statement : 2)));
endif;

if input.Length_of_Host_Variable_List > 0;
json_append(buf : ',');
json_key(buf : 'host_variable_list');
based_ucs2_ptr = pInput + input.Offset_to_Host_Variable_List;
json_escape_value(buf
: %subst(based_ucs2 : 1
: %div(Input.Length_of_Host_Variable_List : 2)));
endif;

230 IBM i: Performance and Query Optimization


json_append(buf : '}');

if buf.truncated;
Qp0zLprintf('SEND_JSON ran out of allocated space for '
+ 'constructing the Query Supervisor JSON data.' + NEWLINE_CH);
endif;

QSNDDTAQ(DataQName
: DataQLib
: buf.curptr - buf.baseptr
: based_buf_data);

begsr initEscapeAction;

jsonEscapeAction =
%list(
// x'00'
UTF16 : UTF16 : UTF16 : UTF16 :
UTF16 : UTF16 : UTF16 : UTF16 :
Backspace :Tab : Newline : UTF16 :
Formfeed : CR : UTF16 : UTF16 :
// x'10'
UTF16 : UTF16 : UTF16 : UTF16 :
UTF16 : UTF16 : UTF16 : UTF16 :
UTF16 : UTF16 : UTF16 : UTF16 :
UTF16 : UTF16 : UTF16 : UTF16 :
// x'20'
None : None : Quote : None :
None : None : None : None :
None : None : None : None :
None : None : None : None :
// x'30'
None : None : None : None :
None : None : None : None :
None : None : None : None :
None : None : None : None :
// x'40'
None : None : None : None :
None : None : None : None :
None : None : None : None :
None : None : None : None :
// x'50'
None : None : None : None :
None : None : None : None :
None : None : None : None :
Backslash :None : None : None :
// x'60'
None : None : None : None :
None : None : None : None :
None : None : None : None :
None : None : None : None :
// x'70'
None : None : None : None :
None : None : None : None :
None : None : None : None :
None : None : None : None :
// x'80'
UTF16 : UTF16 : UTF16 : UTF16 :
UTF16 : UTF16 : UTF16 : UTF16 :
UTF16 : UTF16 : UTF16 : UTF16 :
UTF16 : UTF16 : UTF16 : UTF16 :
// x'90'
UTF16 : UTF16 : UTF16 : UTF16 :
UTF16 : UTF16 : UTF16 : UTF16 :
UTF16 : UTF16 : UTF16 : UTF16 :
UTF16 : UTF16 : UTF16 : UTF16);
endsr;

on-exit;
dealloc buf.baseptr;
end-proc;

// Copies a UTF-16 source stream to a UTF-16 target stream, escaping


// JSON characters as needed.
dcl-proc json_escape;
dcl-pi *n varucs2(MAX_TARGET_LEN) rtnparm;
source varucs2(MAX_SOURCE_LEN) const;
end-pi;
dcl-s i int(10);
dcl-ds ucs2_to_num qualified;
c ucs2(1);
n uns(5) overlay(c);

Database performance and query optimization 231


end-ds;
dcl-s action int(10);
dcl-s target_pos int(10);
dcl-s target varucs2(40000) inz(*blanks);
dcl-s c ucs2(1);
dcl-s c_num packed(5);

// Loop through all the source UTF-16 characters, copying any that
// do not require escaping, and escaping those that are required.
target_pos = 1;
for i = 1 to %len(source);
c = %subst(source : i : 1);
ucs2_to_num.c = c;
c_num = ucs2_to_num.n;

// Is the current character in the defined escapable range?


if c_num <= %elem(JsonEscapeAction);
action = JsonEscapeAction(c_num + 1);
else;
action = None;
endif;

if action = None;
// No escaping needed. Emit the source character.
%subst(target : target_pos : 1) = c;
target_pos += 1;
else;
%subst(target : target_pos : 1) =
%subst(EscapeChars : Backslash + 1 : 1);
target_pos += 1;
if action = UTF16;
// We escape this as a UTF16 codepoint: \u00XX
%subst(target : target_pos : %len(UnicodePrefix)) = UnicodePrefix;
target_pos += %len(UnicodePrefix);
%subst(target : target_pos : 1) =
%subst(HexChars : %div(c_num : 16) + 1 : 1);
target_pos += 1;
%subst(target : target_pos : 1) =
%subst(HexChars : %rem(c_num : 16) + 1 : 1);
target_pos += 1;
else;
// We escape this as a special character: e.g. \t
%subst(target : target_pos : 1) =
%subst(EscapeChars : Action + 1 : 1);
target_pos += 1;
endif;
endif;
endfor;

return %subst(target : 1 : target_pos - 1);


end-proc json_escape;

// Returns *on if the buffer space can accommodate "len" Unicode chars
// Returns *off and sets the truncated flag if otherwise.
dcl-proc buffer_has_space;
dcl-pi *n ind;
buf likeds(BufferInfo_t);
len int(10) value;
end-pi;
dcl-s required_buf_len int(10);

required_buf_len = (buf.curptr - buf.baseptr) + (len * 2);


if required_buf_len <= buf.allocsize;
return *on;
else;
buf.truncated = *on;
return *off;
endif;
end-proc;

// JSON_KEY takes a null-terminated UTF-16 string, delimits


// it with quotes, adds a colon (:), and outputs it to the
// output buffer.
dcl-proc json_key;
dcl-pi *n;
buf likeds(BufferInfo_t);
key varucs2(MAX_SOURCE_LEN) const;
end-pi;

dcl-s string ucs2(MAX_TARGET_LEN) based(buf.curptr);

232 IBM i: Performance and Query Optimization


if buffer_has_space (buf : %len(key) + 3);
%subst(string : 1 : 1) = '"';
buf.curptr += 2;
%subst(string : 1 : %len(key)) = key;
buf.curptr += 2 * %len(key);
%subst(string : 1 : 2) = '":';
buf.curptr += 4;
endif;
end-proc;

// json_string_value takes string,


// delimits it with quotes, and
// outputs it to the output buffer.
dcl-proc json_string_value;
dcl-pi
*n;

buf likeds(BufferInfo_t);
string varucs2(MAX_SOURCE_LEN) const;
end-pi;

dcl-s buf_string ucs2(MAX_TARGET_LEN) based(buf.curptr);

if buffer_has_space (buf : %len(string) + 2);


%subst(buf_string : 1 : 1) = '"';
buf.curptr += 2;
%subst(buf_string : 1 : %len(string)) = string;
buf.curptr += 2 * %len(string);
%subst(buf_string : 1 : 1) = '"';
buf.curptr += 2;
endif;
end-proc;

// json_numeric_value takes a numeric value


// converts it to UTF-16 and
// outputs it to the output buffer.
dcl-proc json_numeric_value;
dcl-pi *n;
buf likeds(BufferInfo_t);
num int(20) value;
end-pi;

dcl-s json_string varucs2(MAX_TARGET_LEN);


dcl-s buf_string ucs2(MAX_TARGET_LEN) based(buf.curptr);

json_string = %char(num);

if buffer_has_space (buf : %len(json_string));


%subst(buf_string : 1 : %len(json_string)) = json_string;
buf.curptr += 2 * %len(json_string);
endif;
end-proc;

// json_escape_value takes a UTF-16 string of a given size


// and outputs it to the output buffer after delimiting it
// and escaping any characters as defined by the JSON standard.
dcl-proc json_escape_value;
dcl-pi *n;
buf likeds(BufferInfo_t);
string varucs2(MAX_SOURCE_LEN) const;
end-pi;

dcl-s buf_string ucs2(MAX_TARGET_LEN) based(buf.curptr);


dcl-s json_string varucs2(MAX_TARGET_LEN);

json_string = json_escape (string);

if buffer_has_space (buf : %len(json_string) + 2);


%subst(buf_string : 1 : 1) = '"';
buf.curptr += 2;
%subst(buf_string : 1 : %len(json_string)) = json_string;
buf.curptr += 2 * %len(json_string);
%subst(buf_string : 1 : 1) = '"';
buf.curptr += 2;
endif;
end-proc;

// JSON_APPEND takes a UTF-16 string and


// outputs it to the output buffer.
dcl-proc json_append;
dcl-pi *n;
buf likeds(BufferInfo_t);

Database performance and query optimization 233


string varucs2(MAX_SOURCE_LEN) const;
end-pi;
dcl-s buf_string ucs2(MAX_TARGET_LEN) based(buf.curptr);

if buffer_has_space (buf : %len(string));


%subst(buf_string : 1 : %len(string)) = string;
buf.curptr += 2 * %len(string);
endif;

end-proc;

C exit program to log information using a data queue


This Query Supervisor exit program shows how to use an asynchronous job to log information about the
query that reported a threshold.
This is the registered exit program. It sends the exit program input data to a data queue named
SUPERVISOR/SUPER_DQ for further processing by an SQL procedure. The data is sent as a JSON object,
encoded as UTF-16 data.
To compile this C program, use the following commands. By using USRPRF(*OWNER), *PUBLIC does not
need to be given access to the objects used by this program. The owning profile of the created program
must have authority to the commands and objects used by the exit program.

CRTCMOD MODULE(SUPERVISOR/SEND_JSON) SRCFILE(SUPERVISOR/QCSRC) LOCALETYPE(*LOCALEUCS2)

CRTPGM PGM(SUPERVISOR/SEND_JSON) USRPRF(*OWNER) ACTGRP(*CALLER)

The program can be registered as an exit program using this command:

ADDEXITPGM EXITPNT(QIBM_QQQ_QRY_SUPER) FORMAT(QRYS0100) PGMNBR(*LOW) PGM(SUPERVISOR/SEND_JSON)


THDSAFE(*YES) TEXT('Query Supervisor logging with data queue')

#include <except.h>
#include <decimal.h>
#include <qsnddtaq.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <iconv.h>
#include <assert.h>
#include <time.h>
#include <qp0ztrc.h>
#include <eqqqrysv.h>

/* Properties of the data queue that we will send the JSON to: */
char* DataQLib = "SUPERVISOR";
char* DataQName = "SUPER_DQ ";
const int DataQMaxBytes = 45000;

/* Define a lookup table that indicates how to handle escapable JSON


characters. Each entry represents one of the first 160 UTF-16
codepoints. */
enum EscapeAction
{None,UTF16,Backspace,Tab,Newline,Formfeed,CR,Quote,Backslash};
char JsonEscapeAction[160]={
/*x00*/ UTF16, UTF16, UTF16, UTF16,
UTF16, UTF16, UTF16, UTF16,
Backspace,Tab, Newline, UTF16,
Formfeed, CR, UTF16, UTF16,
/*x10*/ UTF16, UTF16, UTF16, UTF16,
UTF16, UTF16, UTF16, UTF16,
UTF16, UTF16, UTF16, UTF16,
UTF16, UTF16, UTF16, UTF16,
/*x20*/ None, None, Quote, None,
None, None, None, None,
None, None, None, None,
None, None, None, None,
/*x30*/ None, None, None, None,
None, None, None, None,
None, None, None, None,
None, None, None, None,
/*x40*/ None, None, None, None,
None, None, None, None,
None, None, None, None,

234 IBM i: Performance and Query Optimization


None, None, None, None,
/*x50*/ None, None, None, None,
None, None, None, None,
None, None, None, None,
Backslash,None, None, None,
/*x60*/ None, None, None, None,
None, None, None, None,
None, None, None, None,
None, None, None, None,
/*x70*/ None, None, None, None,
None, None, None, None,
None, None, None, None,
None, None, None, None,
/*x80*/ UTF16, UTF16, UTF16, UTF16,
UTF16, UTF16, UTF16, UTF16,
UTF16, UTF16, UTF16, UTF16,
UTF16, UTF16, UTF16, UTF16,
/*x90*/ UTF16, UTF16, UTF16, UTF16,
UTF16, UTF16, UTF16, UTF16,
UTF16, UTF16, UTF16, UTF16,
UTF16, UTF16, UTF16, UTF16
};

/* Define constants used for generating JSON escape sequences. */


const wchar_t HexChars[17]=L"0123456789ABCDEF";
const wchar_t EscapeChars[10]= L" btnfr\"\\";
const wchar_t UnicodePrefix[4]= L"u00";

/* Copies a UTF-16 source stream to a UTF-16 target stream, escaping


JSON characters as needed. */
void json_escape(wchar_t** target, int target_length,
const wchar_t* source, int source_length)
{
const wchar_t** target_end = target + target_length;

/* Loop through all the source UTF-16 characters, copying any that
do not require escaping, and escaping those that are required. */
while (source_length-- && target < target_end)
{
const wchar_t c = *source;
enum EscapeAction action;

/* Is the current character in the defined escapable range? */


if(c<(sizeof(JsonEscapeAction)/sizeof(JsonEscapeAction[0])))
action = (enum EscapeAction)JsonEscapeAction[c];
else
action = None;

if (action == None)
{
/* No escaping needed. Emit the source character. */
**target = c;
++*target;
}
else
{
**target = EscapeChars[Backslash];
++*target;
if (action == UTF16)
{
if (target+6 >= target_end)
break;

/* We escape this as a UTF16 codepoint: \u00XX */


memcpy(*target, UnicodePrefix, sizeof(UnicodePrefix)-2);
*target += sizeof(UnicodePrefix)/2-1;

**target = HexChars[c >> 4];


++*target;

**target = HexChars[c & 0x0f];


++*target;
}
else
{
if (target >= target_end)
break;

/* We escape this as a special character: e.g. \t */


**target = EscapeChars[action];
++*target;
}

Database performance and query optimization 235


}
++source;
}
}

/* Uses iconv to convert an input string in Job CCSID to UTF-16. */


size_t convert_to_utf16(const char* input, size_t input_bytes,
wchar_t** output, size_t output_bytes,
iconv_t converter)
{
int iconv_rc;
int original_output_bytes = output_bytes;
iconv_rc = iconv(converter,
&input, &input_bytes,
(char**)output, &output_bytes);

/* If conversion was successful, we'll return the number of bytes that


were produced. */
if (iconv_rc >= 0)
return original_output_bytes - output_bytes;

/* Conversion was unsuccessful. Put an ERROR value in the output if


there is room. */
if (original_output_bytes >= 10)
{
memcpy(*output, L"ERROR", 10);
*output+=5;
return 10;
}

return 0;
}

/* Returns the trimmed length of the given wide string after


discarding any trailing blanks. */
size_t wtrimmed_length(const wchar_t* input, size_t input_len)
{
while (input_len && input[input_len-1] == L' ')
{--input_len;}

return input_len;
}

/* Returns the trimmed length of the given string after


discarding any trailing blanks. */
size_t trimmed_length(const char* input, size_t input_len)
{
while (input_len && input[input_len-1] == ' ')
{--input_len;}

return input_len;
}

/* Defines properties for the buffer containing the JSON payload. */


typedef struct BufferInfo
{
volatile wchar_t* baseptr;
wchar_t* curptr;
int allocsize;
volatile iconv_t converter;
int truncated;
} BufferInfo_t;

/* Calculates the bytes allocated but unused for a given BufferInfo


object. */
#define BYTES_REMAINING(buf) \
(buf.allocsize - ((char*)buf.curptr-(char*)buf.baseptr))

/* Returns 1 if the buffer space can accommodate "size" bytes.


Returns 0 and sets the truncated flag if otherwise. */
inline int buffer_has_space(BufferInfo_t* buf, int size)
{
if (!buf->truncated &&
BYTES_REMAINING((*buf)) >= size)
return 1;

buf->truncated = 1;
return 0;
}

236 IBM i: Performance and Query Optimization


/* JSON_KEY takes a null-terminated UTF-16 string, delimits
it with quotes, adds a colon (:), and outputs it to the
output buffer. */
#define JSON_KEY(buf, key) \
if (buffer_has_space(&buf, 6 + (sizeof(key)-2))) \
{ \
wcscpy(buf.curptr, L"\""); ++buf.curptr; \
wcscpy(buf.curptr,key); buf.curptr+=(sizeof(key)/2)-1; \
wcscpy(buf.curptr, L"\":"); buf.curptr+=2; \
}

/* JSON_STRING_VALUE takes a blank-padded string in the job CCSID,


trims trailing blanks, converts the string to UTF-16,
delimits it with quotes, and copies it to the output buffer. */
#define JSON_STRING_VALUE(buf, value) \
if (buffer_has_space(&buf, 2)) \
{ \
wcscpy(buf.curptr, L"\""); ++buf.curptr; \
} \
if (!buf.truncated) \
{\
convert_to_utf16(value, \
trimmed_length(value, sizeof(value)), \
&buf.curptr, \
BYTES_REMAINING(buf), \
buf.converter); \
}\
if (buffer_has_space(&buf,2)) \
{ \
wcscpy(buf.curptr, L"\""); ++buf.curptr; \
}

/* JSON_NUMERIC_VALUE takes a UTF-16 string of a given size


and outputs it to the output buffer. */
#define JSON_NUMERIC_VALUE(buf, value, count) \
if (buffer_has_space(&buf, count * 2)) \
{ \
wcsncpy(buf.curptr, value, count); buf.curptr+=count; \
}

/* JSON_ESCAPE_VALUE takes a UTF-16 string of a given size


and outputs it to the output buffer after delimiting it
and escaping any characters as defined by the JSON standard. */
#define JSON_ESCAPE_VALUE(buf, value, count) \
if (buffer_has_space(&buf, 2)) \
{ \
wcscpy(buf.curptr, L"\""); ++buf.curptr; \
} \
if (!buf.truncated) \
{\
json_escape(&buf.curptr, \
BYTES_REMAINING(buf) / 2, \
value, \
count); \
}\
if (buffer_has_space(&buf,2)) \
{ \
wcscpy(buf.curptr, L"\""); ++buf.curptr; \
}

/* JSON_APPEND takes a null-terminated UTF-16 string and


outputs it to the output buffer. */
#define JSON_APPEND(buf, string) \
if (buffer_has_space(&buf, sizeof(string)-2)) \
{ \
wcscpy(buf.curptr, string); buf.curptr += (sizeof(string)/2)-1; \
}

/* Cleanup handler function to ensure all resources are freed */


void cleanup(_CNL_Hndlr_Parms_T* cancel_info)
{
Qp0zLprintf("SEND_JSON is cleaning up \n");
BufferInfo_t* buf = (BufferInfo_t*)(cancel_info->Com_Area);
free((void*)buf->baseptr);
iconv_close(buf->converter);
}

int main(int argc, char* argv[])


{
const QQQ_QRYSV_QRYS0100_t* input = (QQQ_QRYSV_QRYS0100_t*)argv[1];

Database performance and query optimization 237


int* rc = (int*)argv[2];

BufferInfo_t buf;
wchar_t translate_buffer[1024];
time_t current_time;
size_t char_count;
wchar_t* work_ptr;
size_t converted_bytes;
struct tm *timeptr;
char* inputAsCharData;
char from_code[32], to_code[32];

/* Don't terminate the query */


*rc = 0;

/* Set up the buffer used for the final JSON payload. */


buf.baseptr = (wchar_t*)malloc(DataQMaxBytes);
buf.allocsize = DataQMaxBytes;
buf.curptr = (wchar_t*) buf.baseptr;
buf.truncated = 0;

/* Prepare the CCSID converter. We convert from Job CCCSID


to CCSID 1200 (UTF-16). */
memset(from_code, 0, sizeof(from_code));
memset(to_code, 0, sizeof(to_code));
memcpy(from_code, "IBMCCSID000000000000", 20);
memcpy(to_code, "IBMCCSID01200", 13);
buf.converter = iconv_open(to_code, from_code);
assert(buf.converter.return_value == 0);

#pragma cancel_handler (cleanup, buf)

/* JSON encoding starts here. */


JSON_APPEND(buf, L"{");

/* Insert fixed length fields from the input.


All fields must be converted into UTF-16 strings, except
for the threshold name, which is already UTF-16. */

JSON_KEY(buf, L"threshold_timestamp");
JSON_APPEND(buf, L"\"");
current_time = time(NULL);
timeptr = localtime(&current_time);
char_count = wcsftime(buf.curptr,
sizeof(translate_buffer)/2,
L"%F %T",
timeptr);
buf.curptr += char_count;
JSON_APPEND(buf, L"\"");

JSON_APPEND(buf, L",");
JSON_KEY(buf, L"job_name");
JSON_STRING_VALUE(buf, input->Job_Name);

JSON_APPEND(buf, L",");
JSON_KEY(buf, L"job_user");
JSON_STRING_VALUE(buf, input->Job_User);

JSON_APPEND(buf, L",");
JSON_KEY(buf, L"job_number");
JSON_STRING_VALUE(buf, input->Job_Number);

JSON_APPEND(buf, L",");
JSON_KEY(buf, L"subsystem");
JSON_STRING_VALUE(buf, input->Subsystem);

JSON_APPEND(buf, L",");
JSON_KEY(buf, L"user_name");
JSON_STRING_VALUE(buf, input->User_Name);

JSON_APPEND(buf, L",");
JSON_KEY(buf, L"query_identifier");
JSON_STRING_VALUE(buf, input->Query_Identifier);

JSON_APPEND(buf, L",");
JSON_KEY(buf, L"query_plan_identifier");
char_count = swprintf(translate_buffer,
sizeof(translate_buffer)/2,
L"%llu",
input->Plan_Identifier);
JSON_NUMERIC_VALUE(buf, translate_buffer, char_count);

238 IBM i: Performance and Query Optimization


JSON_APPEND(buf, L",");
JSON_KEY(buf, L"threshold_name");
JSON_ESCAPE_VALUE(buf,
(wchar_t*)(input->Threshold_Name),
wtrimmed_length((wchar_t*)(input->Threshold_Name),
sizeof(input->Threshold_Name)/2));

JSON_APPEND(buf, L",");
JSON_KEY(buf, L"threshold_type");
JSON_STRING_VALUE(buf, input->Threshold_Type);

JSON_APPEND(buf, L",");
JSON_KEY(buf, L"threshold_consumption_value");
char_count = swprintf(translate_buffer,
sizeof(translate_buffer)/2,
L"%lld",
input->Threshold_Consumption_Value);
JSON_NUMERIC_VALUE(buf, translate_buffer, char_count);

JSON_APPEND(buf, L",");
char_count = swprintf(translate_buffer,
sizeof(translate_buffer)/2,
L"%d",
(int)input->Operation_Type);
JSON_KEY(buf, L"operation_type");
JSON_NUMERIC_VALUE(buf, translate_buffer, char_count);

/* Insert variable length fields.


Client special registers need to be translated to UTF-16
before they can be escaped and inserted.
The SQL statement text and the host variable list can be
copied over (with JSON escaping) as they are, since they
are passed in as UTF-16 data. */

inputAsCharData = (char*)input;

if (input->Length_of_CLIENT_ACCTNG)
{
JSON_APPEND(buf, L",");
JSON_KEY(buf, L"client_acctng");
work_ptr = translate_buffer;
converted_bytes =
convert_to_utf16(inputAsCharData+input->Offset_to_CLIENT_ACCTNG,
input->Length_of_CLIENT_ACCTNG,
&work_ptr,
sizeof(translate_buffer),
buf.converter);
JSON_ESCAPE_VALUE(buf, translate_buffer, converted_bytes / 2);
}

if (input->Length_of_CLIENT_APPLNAME)
{
JSON_APPEND(buf, L",");
JSON_KEY(buf, L"client_applname");
work_ptr = translate_buffer;
converted_bytes =
convert_to_utf16(inputAsCharData+input->Offset_to_CLIENT_APPLNAME,
input->Length_of_CLIENT_APPLNAME,
&work_ptr,
sizeof(translate_buffer),
buf.converter);
JSON_ESCAPE_VALUE(buf, translate_buffer, converted_bytes / 2);
}

if (input->Length_of_CLIENT_PROGRAMID)
{
JSON_APPEND(buf, L",");
JSON_KEY(buf, L"client_programid");
work_ptr = translate_buffer;
converted_bytes =
convert_to_utf16(inputAsCharData+input->Offset_to_CLIENT_PROGRAMID,
input->Length_of_CLIENT_PROGRAMID,
&work_ptr,
sizeof(translate_buffer),
buf.converter);
JSON_ESCAPE_VALUE(buf, translate_buffer, converted_bytes / 2);
}

if (input->Length_of_CLIENT_USERID)
{
JSON_APPEND(buf, L",");

Database performance and query optimization 239


JSON_KEY(buf, L"client_userid");
work_ptr = translate_buffer;
converted_bytes =
convert_to_utf16(inputAsCharData+input->Offset_to_CLIENT_USERID,
input->Length_of_CLIENT_USERID,
&work_ptr,
sizeof(translate_buffer),
buf.converter);
JSON_ESCAPE_VALUE(buf, translate_buffer, converted_bytes / 2);
}

if (input->Length_of_CLIENT_WRKSTNNAME)
{
JSON_APPEND(buf, L",");
JSON_KEY(buf, L"client_wrkstnname");
work_ptr = translate_buffer;
converted_bytes =
convert_to_utf16(inputAsCharData+input->Offset_to_CLIENT_WRKSTNNAME,
input->Length_of_CLIENT_WRKSTNNAME,
&work_ptr,
sizeof(translate_buffer),
buf.converter);
JSON_ESCAPE_VALUE(buf, translate_buffer, converted_bytes / 2);
}

if (input->Length_of_SQL_Statement)
{
JSON_APPEND(buf, L",");
JSON_KEY(buf, L"sql_statement_text");
JSON_ESCAPE_VALUE(buf,
(wchar_t*)(inputAsCharData+input->Offset_to_SQL_Statement),
input->Length_of_SQL_Statement/2);
}

if (input->Length_of_Host_Variable_List)
{
JSON_APPEND(buf, L",");
JSON_KEY(buf, L"host_variable_list");
JSON_ESCAPE_VALUE(buf,
(wchar_t*)(inputAsCharData+input->Offset_to_Host_Variable_List),
input->Length_of_Host_Variable_List/2);
}

JSON_APPEND(buf, L"}");

if (buf.truncated)
{
Qp0zLprintf("SEND_JSON ran out of allocated space for "
"constructing the Query Supervisor JSON data.\n");
}

QSNDDTAQ(DataQName,
DataQLib,
(decimal(5,0))((char*)buf.curptr-(char*)buf.baseptr),
(void *)buf.baseptr
);

#pragma disable_handler

free((void*)buf.baseptr);
iconv_close(buf.converter);

return 0;
}

SQL procedure used to log information using a data queue


This SQL procedure, running in an asynchronous job, logs information about the query that reported a
threshold.
The procedure receives entries from the SUPERVISOR/SUPER_DQ data queue. Each entry represents
an instance of a Query Supervisor threshold having been met or exceeded. The Query Supervisor exit
program that got control put the entry on the data queue so it could be handled asynchronously by this
SQL procedure.

240 IBM i: Performance and Query Optimization


Using MONITOR = *SYSTEM, ensures that the procedure’s activity is not supervised by Query Supervisor.
This prevents possible recursion if the procedure itself were to reach a Query Supervisor threshold.

create or replace procedure supervisor.process_QS_data_queue ()


modifies sql data
set option commit = *none, datfmt = *usa, datsep = *slash, output = *print, monitor =
*system
begin
declare local_sqlcode integer;
declare local_sqlstate char(5) for sbcs data;
declare v_message_text varchar(200) for sbcs data;
declare v_message_data_utf8 clob(63k) ccsid 1208;
declare v_message_data_binary blob(63k);
declare v_message_data_binary_length integer;
declare v_threshold_timestamp timestamp;
declare v_job_name varchar(10) ccsid 1208;
declare v_job_user varchar(10) ccsid 1208;
declare v_job_number varchar(6) ccsid 1208;
declare v_subsystem varchar(10) ccsid 1208;
declare v_user_name varchar(10) ccsid 1208;
declare v_threshold_name varchar(30) ccsid 1208;
declare v_threshold_type varchar(30) ccsid 1208;
declare v_threshold_consumption_value bigint;
declare v_operation_type smallint;
declare v_sql_statement_text varchar(10000) ccsid 1208;
declare v_host_variable_list varchar(10000) ccsid 1208;
declare v_client_acctng varchar(255) ccsid 1208;
declare v_client_applname varchar(255) ccsid 1208;
declare v_client_programid varchar(255) ccsid 1208;
declare v_client_userid varchar(255) ccsid 1208;
declare v_client_wrkstnname varchar(255) ccsid 1208;
declare v_query_identifier varchar(8) ccsid 1208;
declare v_query_plan_identifier decimal(20,0);
declare continue handler for sqlexception
begin
get diagnostics condition 1
local_sqlcode = db2_returned_sqlcode, local_sqlstate = returned_sqlstate,
v_message_text = message_text;
call systools.lprintf('process_QS_data_queue() - failed with SQLCODE:' concat
error_sqlcode concat ' SQLSTATE:' concat error_sqlstate concat ' and MESSAGE:'
concat v_message_text);
end; /* end of continue handler */
while (1 = 1) do
select MESSAGE_DATA_BINARY
into v_message_data_binary
from
table (
qsys2.receive_data_queue(
data_queue => 'SUPER_DQ', data_queue_library => 'SUPERVISOR',
wait_time => -1) -- any negative means to wait forever for the next message
);

-- Convert the UTF16 data to UTF8


set v_message_data_binary_length = length(v_message_data_binary) / 2;
set v_message_data_utf8 = (
select
interpret(
varbinary_format(hex(v_message_data_binary_length)) concat v_message_data_binary
as dbclob(63k) ccsid 1200)
from sysibm.sysdummy1);

select THRESHOLD_TIMESTAMP, JOB_NAME, JOB_USER, JOB_NUMBER, SUBSYSTEM, USER_NAME,


THRESHOLD_NAME, THRESHOLD_TYPE, THRESHOLD_CONSUMPTION_VALUE, OPERATION_TYPE,
SQL_STATEMENT_TEXT, HOST_VARIABLE_LIST, CLIENT_ACCTNG, CLIENT_APPLNAME,
CLIENT_PROGRAMID, CLIENT_USERID, CLIENT_WRKSTNNAME, QUERY_IDENTIFIER,
QUERY_PLAN_IDENTIFIER
into v_THRESHOLD_TIMESTAMP, v_JOB_NAME, v_JOB_USER, v_JOB_NUMBER, v_SUBSYSTEM,
v_USER_NAME, v_THRESHOLD_NAME, v_THRESHOLD_TYPE, v_THRESHOLD_CONSUMPTION_VALUE,
v_OPERATION_TYPE, v_SQL_STATEMENT_TEXT, v_HOST_VARIABLE_LIST,
v_CLIENT_ACCTNG, v_CLIENT_APPLNAME, v_CLIENT_PROGRAMID, v_CLIENT_USERID,
v_CLIENT_WRKSTNNAME, v_QUERY_IDENTIFIER, v_QUERY_PLAN_IDENTIFIER
from
json_table(
v_message_data_utf8,
'$'
columns(
threshold_timestamp timestamp path 'lax $.threshold_timestamp',
job_name varchar(10) path 'lax $.job_name',
job_user varchar(10) path 'lax $.job_user',
job_number varchar(6) path 'lax $.job_number',

Database performance and query optimization 241


subsystem varchar(10) path 'lax $.subsystem',
user_name varchar(10) path 'lax $.user_name',
threshold_name varchar(30) path 'lax $.threshold_name',
threshold_type varchar(30) path 'lax $.threshold_type',
threshold_consumption_value bigint path
'lax $.threshold_consumption_value',
operation_type smallint path 'lax $.operation_type',
sql_statement_text varchar(10000) path 'lax $.sql_statement_text',
host_variable_list varchar(10000) path 'lax $.host_variable_list',
client_acctng varchar(255) path 'lax $.client_acctng',
client_applname varchar(255) path 'lax $.client_applname',
client_programid varchar(255) path 'lax $.client_programid',
client_userid varchar(255) path 'lax $.client_userid',
client_wrkstnname varchar(255) path 'lax $.client_wrkstnname',
query_identifier varchar(8) path 'lax $.query_identifier',
query_plan_identifier bigint path 'lax $.query_plan_identifier'
)
);
insert into SQE_QUERY_SUPERVISOR.SUPERVISOR_LOG (
THRESHOLD_TIMESTAMP, JOB_NAME, JOB_USER, JOB_NUMBER, SUBSYSTEM, USER_NAME,
THRESHOLD_NAME, THRESHOLD_TYPE, THRESHOLD_CONSUMPTION_VALUE, OPERATION_TYPE,
SQL_STATEMENT_TEXT, HOST_VARIABLE_LIST, CLIENT_ACCTNG, CLIENT_APPLNAME,
CLIENT_PROGRAMID, CLIENT_USERID, CLIENT_WRKSTNNAME, QUERY_IDENTIFIER,
QUERY_PLAN_IDENTIFIER)
values (v_THRESHOLD_TIMESTAMP, v_JOB_NAME, v_JOB_USER, v_JOB_NUMBER, v_SUBSYSTEM,
v_USER_NAME, v_THRESHOLD_NAME, v_THRESHOLD_TYPE, v_THRESHOLD_CONSUMPTION_VALUE,
v_OPERATION_TYPE, v_SQL_STATEMENT_TEXT, v_HOST_VARIABLE_LIST, v_CLIENT_ACCTNG,
v_CLIENT_APPLNAME, v_CLIENT_PROGRAMID, v_CLIENT_USERID, v_CLIENT_WRKSTNNAME,
v_QUERY_IDENTIFIER, v_QUERY_PLAN_IDENTIFIER);
end while;
end;

Setting resource limits with the Predictive Query Governor


The Db2 for i Predictive Query Governor can stop the initiation of a query if the estimated run time
(elapsed execution time) or estimated temporary storage for the query is excessive. The governor acts
before a query is run instead of while a query is run. The governor can be used in any interactive or batch
job on the system. It can be used with all Db2 for i query interfaces and is not limited to use with SQL
queries.
The ability of the governor to predict and stop queries before they are started is important because:
• Operating a long-running query and abnormally ending the query before obtaining any results wastes
system resources.
• Some CQE operations within a query cannot be interrupted by the End Request (ENDRQS) CL
command. The creation of a temporary index or a query using a column function without a GROUP BY
clause are two examples of these types of queries. It is important to not start these operations if they
take longer than the user wants to wait.
The governor in Db2 for i is based on two measurements:
• The estimated runtime for a query.
• The estimated temporary storage consumption for a query.
If the query estimated runtime or temporary storage usage exceed the user-defined limits, the initiation
of the query can be stopped.
To define a time limit (in seconds) for the governor to use, do one of the following:
• Use the Query Time Limit (QRYTIMLMT) parameter on the Change Query Attributes (CHGQRYA)
CL command. The command language used is the first place where the optimizer attempts to find the
time limit.
• Set the Query Time Limit option in the query options file. The query options file is the second place
where the query optimizer attempts to find the time limit.
• Set the QQRYTIMLMT system value. Allow each job to use the value *SYSVAL on the Change Query
Attributes (CHGQRYA) CL command, and set the query options file to *DEFAULT. The system value
is the third place where the query optimizer attempts to find the time limit.

242 IBM i: Performance and Query Optimization


To define a temporary storage limit (in megabytes) for the governor to use, do the following:
• Use the Query Storage Limit (QRYSTGLMT) parameter on the Change Query Attributes
(CHGQRYA) CL command. The command language used is the first place where the query optimizer
attempts to find the limit.
• Set the Query Storage Limit option STORAGE_LIMIT in the query options file. The query options file is
the second place where the query optimizer attempts to find the time limit.
The time and temporary storage values generated by the optimizer are only estimates. The actual query
runtime might be more or less than the estimate. In certain cases when the optimizer does not have full
information about the data being queried, the estimate could vary considerably from the actual resource
used. In those cases, you might need to artificially adjust your limits to correspond to an inaccurate
estimate.
When setting the time limit for the entire system, set it to the maximum allowable time that any query
must be allowed to run. By setting the limit too low you run the risk of preventing some queries from
completing and thus preventing the application from successfully finishing. There are many functions that
use the query component to internally perform query requests. These requests are also compared to the
user-defined time limit.
You can check the inquiry message CPA4259 for the predicted runtime and storage. If the query is
canceled, debug messages are still written to the job log.
You can also add the Query Governor Exit Program that is called when estimated runtime and temporary
storage limits have exceeded the specified limits.
Related information
Query Governor Exit Program
End Request (ENDRQS) command
Change Query Attributes (CHGQRYA) command

Using the Query Governor


The resource governor works with the query optimizer.
When a user issues a request to the system to run a query, the following occurs:
1. The query access plan is created by the optimizer.
As part of the evaluation, the optimizer predicts or estimates the runtime for the query. This estimate
helps determine the best way to access and retrieve the data for the query. In addition, as part of the
estimating process, the optimizer also computes the estimated temporary storage usage for the query.
2. The estimated runtime and estimated temporary storage are compared against the user-defined query
limit currently in effect for the job or user session.
3. If the estimates for the query are less than or equal to the specified limits, the query governor lets the
query run without interruption. No message is sent to the user.
4. If the query limit is exceeded, inquiry message CPA4259 is sent to the user. The message states the
estimates as well as the specified limits. Realize that only one limit needs to be exceeded; it is possible
that you see that only one limit was exceeded. Also, if no limit was explicitly specified by the user, a
large integer value is shown for that limit.
Note: A default reply can be established for this message so that the user does not have the option to
reply. The query request is always ended.
5. If a default message reply is not used, the user chooses to do one of the following:
• End the query request before it is run.
• Continue and run the query even though the estimated value exceeds the associated governor limit.
Setting the resource limits for jobs other than the current job

Database performance and query optimization 243


You can set either or both resource limits for a job other than the current job. You set these limits by using
the JOB parameter on the Change Query Attributes (CHGQRYA) command. Specify either a query
options file library to search (QRYOPTLIB) or a specific QRYTIMLMT, or QRYSTGLMT, or both for that job.
Using the resource limits to balance system resources
After the source job runs the Change Query Attributes (CHGQRYA) command, effects of the
governor on the target job are not dependent upon the source job. The query resource limits remain in
effect for the duration of the job or user session, or until a resource limit is changed by a Change Query
Attributes (CHGQRYA) command.
Under program control, a user might be given different limits depending on the application function
performed, time of day, or system resources available. These limits provide a significant amount of
flexibility when trying to balance system resources with temporary query requirements.

Cancel a query with the Query Governor


When a query is expected to take more resources than the set limit, the governor issues inquiry message
CPA4259.
You can respond to the message in one of the following ways:
• Enter a C to cancel the query. Escape message CPF427F is issued to the SQL runtime code. SQL returns
SQLCODE -666.
• Enter an I to ignore the exceeded limit and let the query run to completion.

Control the default reply to the query governor inquiry message


The system administrator can control whether the interactive user has the option of ignoring the database
query inquiry message by using the Change Job (CHGJOB) CL command.
Changes made include the following:
• If a value of *DFT is specified for the INQMSGRPY parameter of the Change Job (CHGJOB) CL
command, the interactive user does not see the inquiry messages. The query is canceled immediately.
• If a value of *RQD is specified for the INQMSGRPY parameter of the Change Job (CHGJOB) CL
command, the interactive user sees the inquiry. The user must reply to the inquiry.
• If a value of *SYSRPYL is specified for the INQMSGRPY parameter of the Change Job (CHGJOB) CL
command, a system reply list is used to determine whether the interactive user sees the inquiry and
whether a reply is necessary. The system reply list entries can be used to customize different default
replies based on user profile name, user id, or process names. The fully qualified job name is available
in the message data for inquiry message CPA4259. This algorithm allows the keyword CMPDTA to be
used to select the system reply list entry that applies to the process or user profile. The user profile
name is 10 characters long and starts at position 51. The process name is 10 character long and starts
at position 27.
• The following example adds a reply list element that causes the default reply of C to cancel requests for
jobs whose user profile is 'QPGMR'.

ADDRPYLE SEQNBR(56) MSGID(CPA4259) CMPDTA(QPGMR 51) RPY(C)

The following example adds a reply list element that causes the default reply of C to cancel requests for
jobs whose process name is 'QPADEV0011'.

ADDRPYLE SEQNBR(57) MSGID(CPA4259) CMPDTA(QPADEV0011 27) RPY(C)

Related information
Change Job (CHGJOB) command

244 IBM i: Performance and Query Optimization


Testing performance with the query governor
You can use the query governor to test the performance of your queries.
To test the performance of a query with the query governor, do the following:
1. Set the query time limit to zero ( QRYTIMLMT(0) ) using the Change Query Attributes
(CHGQRYA) command or in the INI file. This forces an inquiry message from the governor stating
that the estimated time to run the query exceeds the query time limit.
2. Prompt for message help on the inquiry message and find the same information that you can find by
running the Print SQL Information (PRTSQLINF) command.
The query governor lets you optimize performance without having to run through several iterations of the
query.
Additionally, if the query is canceled, the query optimizer evaluates the access plan and sends the
optimizer debug messages to the job log. This process occurs even if the job is not in debug mode. You
can then review the optimizer tuning messages in the job log to see if additional tuning is needed to obtain
optimal query performance.
This method allows you to try several permutations of the query with different attributes, indexes, and
syntax, or both. You can then determine what performs better through the optimizer without actually
running the query to completion. This process saves on system resources because the actual query of the
data is never done. If the tables to be queried contain many rows, this method represents a significant
savings in system resources.
Be careful when you use this technique for performance testing, because all query requests are stopped
before they are run. This caution is especially important for a CQE query that cannot be implemented in a
single query step. For these types of queries, separate multiple query requests are issued, and then their
results are accumulated before returning the final results. Stopping the query in one of these intermediate
steps gives you only the performance information for that intermediate step, and not for the entire query.
Related information
Print SQL Information (PRTSQLINF) command
Change Query Attributes (CHGQRYA) command

Examples of setting query time limits


You can set the query time limit for the current job or user session using query options file QAQQINI.
Specify the QRYOPTLIB parameter on the Change Query Attributes (CHGQRYA) command. Use a
user library where the QAQQINI file exists with the parameter set to QUERY_TIME_LIMIT, and the value
set to a valid query time limit.
To set the query time limit for 45 seconds you can use the following Change Query Attributes
(CHGQRYA) command:

CHGQRYA JOB(*) QRYTIMLMT(45)

This command sets the query time limit at 45 seconds. If the user runs a query with an estimated runtime
equal to or less than 45 seconds, the query runs without interruption. The time limit remains in effect
for the duration of the job or user session, or until the time limit is changed by the Change Query
Attributes (CHGQRYA) command.
Assume that the query optimizer estimated the runtime for a query as 135 seconds. A message is sent
to the user that stated that the estimated runtime of 135 seconds exceeds the query time limit of 45
seconds.
To set or change the query time limit for a job other than your current job, the Change Query
Attributes (CHGQRYA) command is run using the JOB parameter. To set the query time limit to

Database performance and query optimization 245


45 seconds for job 123456/USERNAME/JOBNAME use the following Change Query Attributes
(CHGQRYA) command:

CHGQRYA JOB(123456/USERNAME/JOBNAME) QRYTIMLMT(45)

This command sets the query time limit at 45 seconds for job 123456/USERNAME/JOBNAME. If job
123456/USERNAME/JOBNAME tries to run a query with an estimated runtime equal to or less than 45
seconds the query runs without interruption. If the estimated runtime for the query is greater than 45
seconds, for example, 50 seconds, a message is sent to the user. The message states that the estimated
runtime of 50 seconds exceeds the query time limit of 45 seconds. The time limit remains in effect
for the duration of job 123456/USERNAME/JOBNAME, or until the time limit for job 123456/USERNAME/
JOBNAME is changed by the Change Query Attributes (CHGQRYA) command.
To set or change the query time limit to the QQRYTIMLMT system value, use the following Change Query
Attributes (CHGQRYA) command:

CHGQRYA QRYTIMLMT(*SYSVAL)

The QQRYTIMLMT system value is used for duration of the job or user session, or until the time limit is
changed by the Change Query Attributes (CHGQRYA) command. This use is the default behavior
for the Change Query Attributes (CHGQRYA) command.
Note: The query time limit can also be set in the INI file, or by using the Change System Value
(CHGSYSVAL) command.
Related information
Change Query Attributes (CHGQRYA) command
Change System Value (CHGSYSVAL) command

Test temporary storage usage with the query governor


The predictive storage governor specifies a temporary storage limit for database queries. You can use
the query governor to test if a query uses any temporary object, such as a hash table, sort, or temporary
index.
To test for usage of a temporary object, do the following:
• Set the query storage limit to zero (QRYSTGLMT(0)) using the Change Query Attributes
(CHGQRYA) command or in the INI file. This forces an inquiry message from the governor anytime
a temporary object is used for the query. The message is sent regardless of the estimated size of the
temporary object.
• Prompt for message help on the inquiry message and find the same information that you can find by
running the Print SQL Information (PRTSQLINF) command. This command allows you to see
what temporary objects were involved.
Related information
Print SQL Information (PRTSQLINF) command
Change Query Attributes (CHGQRYA) command

Examples of setting query temporary storage limits


The temporary storage limit can be specified either in the QAQQINI file or on the Change Query
Attributes (CHGQRYA) command.
You can set the query temporary storage limit for a job using query options file QAQQINI. Specify the
QRYOPTLIB parameter on the Change Query Attributes (CHGQRYA) command. Use a user library
where the QAQQINI file exists with a valid value set for parameter STORAGE_LIMIT.
To set the query temporary storage limit on the Change Query Attributes (CHGQRYA) command
itself, specify a valid value for the QRYSTGLMT parameter.

246 IBM i: Performance and Query Optimization


If a value is specified both on the Change Query Attributes (CHGQRYA) command QRYSTGLMT
parameter and in the QAQQINI file specified on the QRYOPTLIB parameter, the QRYSTGLMT value is used.
To set the temporary storage limit for 100 MB in the current job, you can use the following Change
Query Attributes (CHGQRYA) command:

CHGQRYA JOB(*) QRYSTGLMT(100)

If the user runs any query with an estimated temporary storage consumption equal to or less than 100
MB, the query runs without interruption. If the estimate is more than 100 MB, the CPA4259 inquiry
message is sent by the database. To set or change the query time limit for a job other than your current
job, the CHGQRYA command is run using the JOB parameter. To set the same limit for job 123456/
USERNAME/JOBNAME use the following CHGQRYA command:

CHGQRYA JOB(123456/USERNAME/JOBNAME) QRYSTGLMT(100)

This sets the query temporary storage limit to 100 MBfor job 123456/USERNAME/JOBNAME.
Note: Unlike the query time limit, there is no system value for temporary storage limit. The default
behavior is to let any queries run regardless of their temporary storage usage. The query temporary
storage limit can be specified either in the INI file or on the Change Query Attributes (CHGQRYA)
command.
Related information
Change Query Attributes (CHGQRYA) command

Controlling parallel processing for queries


There are two types of parallel processing available. The first is a parallel I/O that is available at no
charge. The second is Db2 Symmetric Multiprocessing, a feature that you can purchase. You can turn
parallel processing on and off.
Even if parallelism is enabled for a system or job, the individual queries that run in a job might not actually
use a parallel method. This decision might be because of functional restrictions, or the optimizer might
choose a non-parallel method because it runs faster.
Queries processed with parallel access methods aggressively use main storage, CPU, and disk resources.
The number of queries that use parallel processing must be limited and controlled. Activating parallel
processing system wide with the QQRYDEGREE system value is not recommended.
The parallel processing level can be controlled at a system or job level. For a job, either the CURRENT
DEGREE special register or the PARALLEL_DEGREE QAQQINI option can be used.

Controlling system-wide parallel processing for queries


You can use the QQRYDEGREE system value to control parallel processing for a system.
The current value of the system value can be displayed or modified using the following CL commands:
• WRKSYSVAL - Work with System Value
• CHGSYSVAL - Change System Value
• DSPSYSVAL - Display System Value
• RTVSYSVAL - Retrieve System Value
The special values for QQRYDEGREE control whether parallel processing is allowed by default for all jobs
on the system. The possible values are:

*NONE No parallel processing is allowed for database query processing.


*IO I/O parallel processing is allowed for queries.
*OPTIMIZE The query optimizer can choose to use any number of tasks for either I/O or SMP
parallel processing to process the queries. SMP parallel processing is used only if the Db2

Database performance and query optimization 247


Symmetric Multiprocessing feature is installed. The query optimizer chooses to use parallel
processing to minimize elapsed time based on the job share of the memory in the pool.
*MAX The query optimizer can choose to use either I/O or SMP parallel processing to process
the query. SMP parallel processing can be used only if the Db2 Symmetric Multiprocessing
feature is installed. The choices made by the query optimizer are like the choices made for
parameter value *OPTIMIZE. The exception is that the optimizer assumes that all active
memory in the pool can be used to process the query.

The default QQRYDEGREE system value is *NONE. You must change the value if you want parallel query
processing as the default for jobs run on the system.
Changing this system value affects all jobs that is run or are currently running on the system whose
DEGREE query attribute is *SYSVAL. However, queries that have already been started or queries using
reusable ODPs are not affected.

Controlling job level parallel processing for queries


You can also control query parallel processing at the job level using the DEGREE parameter of the
Change Query Attributes (CHGQRYA) command or in the QAQQINI file. You can also use the
SET_CURRENT_DEGREE SQL statement.

Using the Change Query Attributes (CHGQRYA) command


The parallel processing option allowed and, optionally, the number of tasks that can be used when
running database queries in the job can be specified. You can prompt on the Change Query
Attributes (CHGQRYA) command in an interactive job to display the current values of the DEGREE
query attribute.
Changing the DEGREE query attribute does not affect queries that have already been started or queries
using reusable ODPs.
The parameter values for the DEGREE keyword are:

*SAME The parallel degree query attribute does not change.


*NONE No parallel processing is allowed for database query processing.
*IO The CQE optimizer can use any number of tasks when it chooses to use I/O parallel
processing for queries. SMP parallel processing is not allowed. The SQE optimizer
considers I/O parallelism with or without this setting.
*OPTIMIZE The query optimizer can choose to use any number of tasks for either I/O or SMP
parallel processing to process the query. SMP parallel processing can be used only if the
Db2 Symmetric Multiprocessing feature is installed. Use of parallel processing and the
number of tasks used is determined by:
• the number of system processors available
• the job share of active memory available in the pool
• whether the expected elapsed time is limited by CPU processing or I/O resources
The query optimizer chooses an implementation that minimizes elapsed time based on
the job share of the memory in the pool.
*MAX The query optimizer can choose to use either I/O or SMP parallel processing to
process the query. SMP parallel processing can be used only if the Db2 Symmetric
Multiprocessing feature is installed. The choices made by the query optimizer are like
the choices made for parameter value *OPTIMIZE. The exception is that the optimizer
assumes that all active memory in the pool can be used to process the query.
*NBRTASKS Specifies the number of tasks to be used when the query optimizer chooses to use
number-of- SMP parallel processing to process a query. I/O parallelism is also allowed. SMP parallel
tasks processing can be used only if the Db2 Symmetric Multiprocessing feature is installed.

248 IBM i: Performance and Query Optimization


Using a number of tasks less than the number of system processors available restricts
the number of processors used simultaneously for running a query. A larger number
of tasks ensures that the query is allowed to use all the processors available on the
system to run the query. Too many tasks can degrade performance because of the over
commitment of active memory and the overhead cost of managing all the tasks.

*SYSVAL Specifies that the processing option used is set to the current value of the QQRYDEGREE
system value.

The initial value of the DEGREE attribute for a job is *SYSVAL.

Using the SET CURRENT DEGREE SQL statement


You can use the SET CURRENT DEGREE SQL statement to change the value of the CURRENT_DEGREE
special register. The possible values for the CURRENT_DEGREE special register are:

1 No parallel processing is allowed.


2 through Specifies the degree of parallelism that is used.
32767
ANY Specifies that the database manager can choose to use any number of tasks for either
I/O or SMP parallel processing. Use of parallel processing and the number of tasks used
is determined by:
• the number of system processors available
• the job share of active memory available in the pool
• whether the expected elapsed time is limited by CPU processing or I/O resources
The database manager chooses an implementation that minimizes elapsed time based
on the job share of the memory in the pool.
NONE No parallel processing is allowed.
MAX The database manager can choose to use any number of tasks for either I/O or SMP
parallel processing. MAX is like ANY except the database manager assumes that all active
memory in the pool can be used.
IO The CQE optimizer can use any number of tasks when it chooses to use I/O parallel
processing for queries. SMP parallel processing is not allowed. The SQE optimizer
considers I/O parallelism with or without this setting.

The value can be changed by invoking the SET CURRENT DEGREE statement.
The initial value of CURRENT DEGREE comes from the CHGQRYA CL command, PARALLEL_DEGREE
parameter in the current query options file (QAQQINI), or the QQRYDEGREE system value.
Related information
Set Current Degree statement
Change Query Attributes (CHGQRYA) command
DB2 Symmetric Multiprocessing

Collecting statistics with the statistics manager


The collection of statistics is handled by a separate component called the statistics manager. Statistical
information can be used by the query optimizer to determine the best access plan for a query. Since
the query optimizer bases its choice of access plan on the statistical information found in the table, it is
important that this information is current.
On many platforms, statistics collection is a manual process that is the responsibility of the database
administrator. With IBM i products, the database statistics collection process is handled automatically,
and only rarely is it necessary to update statistics manually.

Database performance and query optimization 249


The statistics manager does not actually run or optimize the query. It controls the access to the metadata
and other information that is required to optimize the query. It uses this information to answer questions
posed by the query optimizer. The answers can either be derived from table header information, from
existing indexes, or from single-column statistics.
The use of indexes for estimates includes Maintained Temporary Indexes (MTIs), which the statistics
manager is able to use in the same way as standard permanent indexes. When deciding which index to
use for an estimate, the statistics engine will prioritize permanent indexes over equivalent MTIs.
The statistics manager must always provide an answer to the questions from the Optimizer. It uses
the best method available to provide the answers. For example, it could use a single-column statistic
or perform a key range estimate over an index. Along with the answer, the statistics manager returns
a confidence level to the optimizer that the optimizer can use to provide greater latitude for sizing
algorithms. If the statistics manager provides a low confidence in the number of groups estimated for a
grouping request, the optimizer can increase the size of the temporary hash table allocated.
Related concepts
Statistics manager
In CQE, the retrieval of statistics is a function of the Optimizer. When the Optimizer needs to know
information about a table, it looks at the table description to retrieve the row count and table size.
If an index is available, the Optimizer might extract information about the data in the table. In SQE,
the collection and management of statistics is handled by a separate component called the statistics
manager. The statistics manager leverages all the same statistical sources as CQE, but adds more sources
and capabilities.

Automatic statistics collection


When the statistics manager prepares its responses to the optimizer, it tracks the responses that were
generated using default filter factors. Default filter factors are used when column statistics or indexes are
not available. The statistics manager uses this information to automatically generate a statistic collection
request for the columns. This request occurs while the access plan is written to the plan cache. If system
resources allow, statistics collections occur in real time for direct use by the current query, avoiding a
default answer to the optimizer.
Otherwise, as system resources become available, the requested column statistics are collected in the
background. The next time the query is executed, the missing column statistics are available to the
statistics manager. This process allows the statistics manager to provide more accurate information to
the optimizer at that time. More statistics make it easier for the optimizer to generate a better performing
access plan.
If a query is canceled before or during execution, the requests for column statistics are still processed.
These requests occur if the execution reaches the point where the generated access plan is written to the
Plan Cache.
To minimize the number of passes through a table during statistics collection, the statistics manger
groups multiple requests for the same table. For example, two queries are executed against table T1.
The first query has selection criteria on column C1 and the second over column C2. If no statistics are
available for the table, the statistics manager identifies both of these columns as good candidates for
column statistics. When the statistics manager reviews requests, it looks for multiple requests for the
same table and groups them into one request. This grouping allows both column statistics to be created
with only one pass through table T1.
One thing to note is that column statistics are usually automatically created when the statistics manager
must answer questions from the optimizer using default filter factors. However, when an index is available
that might be used to generate the answer, then column statistics are not automatically generated. In
this scenario, there might be cases where optimization time benefits from column statistics. Using column
statistics to answer questions from the optimizer is more efficient than using the index data. So if query
performance seems extended, you might want to verify that there are indexes over the relevant columns
in your query. If so, try manually generating column statistics for these columns.

250 IBM i: Performance and Query Optimization


As stated before, statistics collection occurs as system resources become available. If you have a
low priority job permanently active on your system that is supposed to use all spare CPU cycles for
processing, your statistics collection is never active.

Automatic statistics refresh


Column statistics are not maintained when the underlying table data changes. The statistics manager
determines if columns statistics are still valid or if they no longer represent the column accurately (stale).
This validation is done each time one of the following occurs:
• A full open occurs for a query where column statistics were used to create the access plan
• A new plan is added to the plan cache, either because a new query was optimized or because an
existing plan was reoptimized.
• A significant number of inserts / updates / deletes have been made to a table. The actual number
of changes before checking the column statistics staleness depends on several factors, including the
number of entries in the table.
To validate the statistics, the statistics manager checks to see if any of the following apply:
• Number of rows in the table has changed by more than 15% of the total table row count
• Number of rows changed in the table is more than 15% of the total table row count
If the statistics are stale, the statistics manager still uses them to answer the questions from the
optimizer. However, the statistics manager marks the statistics as stale in the plan cache and generates a
request to refresh them.

Viewing statistics requests


You can view the current statistics requests by using System i Navigator or by using Statistics APIs.
To view requests in System i Navigator, right-click Database and select Statistic Requests. This window
shows all user requested statistics collections that are pending or active. The view also shows all system
requested statistics collections that are being considered, are active, or have failed. You can change the
status of the request, order the request to process immediately, or cancel the request.
Related reference
Statistics manager APIs
You can use APIs to implement the statistics function of System i Navigator.

Indexes and column statistics


While performing similar functions, indexes and column statistics are different.
If you are trying to decide whether to use statistics or indexes to provide information to the statistics
manager, keep in mind the following differences.
One major difference between indexes and column statistics is that indexes are permanent objects that
are updated when changes to the underlying table occur. Column statistics are not updated. If your data
is constantly changing, the statistics manager might need to rely on stale column statistics. However,
maintaining an index after each table change might use more system resources than refreshing stale
column statistics after a group of changes have occurred.
Another difference is the effect that the existence of new indexes or column statistics has on the
optimizer. When new indexes become available, the optimizer considers them for implementation. If
they are candidates, the optimizer reoptimizes the query and tries to find a better implementation.
However, this reoptimization is not true for column statistics. When new or refreshed column statistics are
available, the statistics manager interrogates immediately. Reoptimization occurs only if the answers are
different from the ones that were given before these refreshed statistics. It is possible to use statistics
that are refreshed without causing a reoptimization of an access plan.

Database performance and query optimization 251


Also, column statistics and EVIs can be used to recognize data skew in joins, which standard radix indexes
are not able to do. So, when join columns contain certain values that occur far more frequently than other
values, column statistics or EVIs may be used to help provide better estimates.
Requests for selectivity information from indexes are obtained in the form of key range estimate
operations. In order to get accurate information for a given predicate, the statistics manager may need
to evaluate a significant portion of an index's data. This evaluation can take a long time for large indexes
as index pages are loaded into active memory and then analyzed. The optimizer must wait for each
estimate operation to complete before continuing with query optimization. Each query that is optimized
will generally require multiple key range estimates. As a result, the time spent obtaining these estimates
can significantly impact the overall time required to optimize a query.
In order to shorten the time required to optimize a query, the statistics manager uses several different
strategies when faced with the need to perform a key range estimate. One strategy is to avoid getting the
estimate when other information (e.g. file size or selectivity information from column statistics) indicate
that the information returned by the estimate would not be worth the time required to obtain it. A second
strategy is to cache prior estimates so that subsequent requests for the same key range can be returned
quickly. Each index has a cache associated with it. Estimates are stored in this cache until the cache fills
or becomes stale relative to the data in the index or until an IPL occurs. A third strategy, introduced in
IBM i 7.3, is to quickly return a less accurate initial estimate while submitting a background request for
a more accurate full estimate. With this strategy, the statistics manager adds a timeout value to each
key range estimate operation. If the operation does not complete in the time indicated by the timeout
value, the operation is interrupted. The statistics manager then looks at some other fast estimate sources
(including similar ranges from the cache and a shallower evaluation of the index) and returns the best
answer obtained thus far. This allows the query to resume optimizing with a reasonable estimate but
without waiting for the full estimate to complete. In the meantime, the QDBFSTCCOL system job will take
up the request to process the full key range estimate and will place an updated (and more accurate) final
result in the estimate cache when it is ready. Once the full estimate is complete and in the cache, any
query which used the initial estimate will have its plan invalidated and re-optimized on the next execution.
The amount of time that the statistics manager waits for a key range estimate to complete can
be configured in the QAQQINI query options file with option KEY_RANGE_ESTIMATE_TIMEOUT. This
control should be seen as a way to influence the optimization time and not as a hard limit . Although
KEY_RANGE_ESTIMATE_TIMEOUT limits the amount of time that the optimizer may take for any
individual estimate operation, it does not guarantee an upper bound on the overall optimization time.
This is because the optimizer may request multiple key range estimates, each of which receives the full
timeout duration.
When trying to determine the selectivity of predicates, the statistics manager considers column statistics
and indexes as resources for its answers in the following orderwith some caveats and exceptions :
1. Try to recognize if an index-based estimate would be very long running, and if so circumvent the index
estimate and use column statistics instead
2. Try to use a multi-column keyed index when ANDed or ORed predicates reference multiple columns
3. If there is no perfect index that contains all the columns in the predicates, it tries to find a combination
of indexes that can be used.
4. For single column questions, it uses available column statistics
5. If the answer derived from the column statistics shows a selectivity of less than 2%, indexes are used
to verify this answer
Accessing column statistics to answer questions is faster than trying to obtain these answers from
indexes.
Column statistics can only be used by SQE. For CQE, all statistics are retrieved from indexes.
Finally, column statistics can be used only for query optimization. They cannot be used for the actual
implementation of a query, whereas indexes can be used for both.

252 IBM i: Performance and Query Optimization


Monitoring background statistics collection
The system value QDBFSTCCOL controls who is allowed to create statistics in the background.
The following list provides the possible values:

*ALL Allows all statistics to be collected in the background. *ALL is the default setting.
*NONE Restricts everyone from creating statistics in the background. *NONE does not prevent
immediate user-requested statistics from being collected, however.
*USER Allows only user-requested statistics to be collected in the background.
*SYSTEM Allows only system-requested statistics to be collected in the background.

When you switch the system value to something other than *ALL or *SYSTEM, the statistics manager
continues to place statistics requests in the plan cache. When the system value is switched back to *ALL,
for example, background processing analyzes the entire plan cache and looks for any existing column
statistics requests. This background task also identifies column statistics that have been used by a plan in
the plan cache. The task determines if these column statistics have become stale. Requests for the new
column statistics as well as requests for refresh of the stale columns statistics are then executed.
All background statistic collections initiated by the system or submitted by a user are performed by
the system job QDBFSTCCOL. User-initiated immediate requests are run within the user job. This job
uses multiple threads to create the statistics. The number of threads is determined by the number of
processors that the system has. Each thread is then associated with a request queue.
There are four types of request queues based on who submitted the request and how long the collection
is estimated to take. The default priority assigned to each thread can determine to which queue the
thread belongs:
• Priority 90 — short user requests
• Priority 93 — long user requests
• Priority 96 — short system requests
• Priority 99 — long system requests
Background statistics collections attempt to use as much parallelism as possible. This parallelism is
independent of the SMP feature installed on the system. However, parallel processing is allowed only
for immediate statistics collection if SMP is installed on the system. The job that requests the column
statistics also must allow parallelism.
Related information
Performance system values: Allow background database statistics collection

Determining what column statistics exist


You can determine what column statistics exist in a couple of ways.
The first is to view statistics by using System i Navigator. Right-click a table or alias and select Statistic
Data. Another way is to create a user-defined table function and call that function from an SQL statement
or stored procedure.

Manually collecting and refreshing statistics


You can manually collect and refresh statistics through System i Navigator or by using statistics APIs.
To collect statistics using System i Navigator, right-click a table or alias and select Statistic Data. On the
Statistic Data dialog, click New. Then select the columns that you want to collect statistics for. Once you
have selected the columns, you can collect the statistics immediately or collect them in the background.
To refresh a statistic using System i Navigator, right-click a table or alias and select Statistic Data. Click
Update. Select the statistic that you want to refresh. You can collect the statistics immediately or collect
them in the background.

Database performance and query optimization 253


There are several scenarios in which the manual management (create, remove, refresh, and so on) of
column statistics could be beneficial and recommended.

High Availability High availability solutions replicate data to a secondary system by using journal
(HA) solutions entries. However, column statistics are not journaled. That means that, on your
backup system, no column statistics are available when you first start using that
system. To prevent the "warm up" effect, you might want to propagate the column
statistics that were gathered on your production system. Recreate them on your
backup system manually.
ISV An ISV might want to deliver a customer solution that already includes column
(Independent statistics frequently used in the application, rather than waiting for the automatic
Software statistics collection to create them. Run the application on the development system
Vendor) for some time and examine which column statistics were created automatically. You
preparation can then generate a script file to execute on the customer system after the initial data
load takes place. The script file can be shipped as part of the application
Business In a large Business Intelligence environment, it is common for large data load and
Intelligence update operations to occur overnight. Column statistics are marked stale only when
environments they are touched by the statistics manager, and then refreshed after first touch. You
might want to consider refreshing the column statistics manually after loading the
data.
You can do this refresh easily by toggling the system value QDBFSTCCOL to *NONE
and then back to *ALL. This process causes all stale column statistics to be refreshed.
It also starts collection of any column statistics previously requested by the system
but not yet available. Since this process relies on the access plans stored in the
plan cache, avoid performing a system initial program load (IPL) before toggling
QDBFSTCCOL. An IPL clears the plan cache.
This procedure works only if you do not delete (drop) the tables and recreate them
in the process of loading your data. When deleting a table, access plans in the plan
cache that refer to this table are deleted. Information about column statistics on that
table is also lost. The process in this environment is either to add data to your tables
or to clear the tables instead of deleting them.

Massive data Updating rows in a column statistics-enabled table can significantly change the
updates cardinality, add new ranges of values, or change the distribution of data values. These
updates can affect query performance on the first query run against the new data. On
the first run of such a query, the optimizer uses stale column statistics to determine
the access plan. At that point, it starts a request to refresh the column statistics.
Prior to this data update, you might want to toggle the system value QDBFSTCCOL
to *NONE and back to *ALL or *SYSTEM. This toggle causes an analysis of the
plan cache. The analysis includes searching for column statistics used in access
plan generation, analyzing them for staleness, and requesting updates for the stale
statistics.
If you massively update or load data, and run queries against these tables at the
same time, the automatic column statistics collection tries to refresh every time 15%
of the data is changed. This processing can be redundant since you are still updating
or loading the data. In this case, you might want to block automatic statistics
collection for the tables and deblock it again after the data update or load finishes.
An alternative is to turn off automatic statistics collection for the whole system before
updating or loading the data. Switch it back on after the updating or loading has
finished.

Backup and When thinking about backup and recovery strategies, keep in mind that creation of
recovery column statistics is not journaled. Column statistics that exist at the time a save
operation occurs are saved as part of the table and restored with the table. Any
column statistics created after the save took place are lost and cannot be recreated

254 IBM i: Performance and Query Optimization


by using techniques such as applying journal entries. If you have a long interval
between save operations and rely on journaling to restore your environment, consider
tracking column statistics that are generated after the latest save operation.

Related information
Performance system values: Allow background database statistics collection

Statistics manager APIs


You can use APIs to implement the statistics function of System i Navigator.
• Cancel Requested Statistics Collections (QDBSTCRS,
QdbstCancelRequestedStatistics) immediately cancels statistics collections that have been
requested, but are not yet completed or not successfully completed.
• Delete Statistics Collections (QDBSTDS, QdbstDeleteStatistics) immediately
deletes existing completed statistics collections.
• List Requested Statistics Collections (QDBSTLRS,
QdbstListRequestedStatistics) lists all the columns and combination of columns and file
members that have background statistic collections requested, but not yet completed.
• List Statistics Collection Details (QDBSTLDS, QdbstListDetailStatistics) lists
additional statistics data for a single statistics collection.
• List Statistics Collections (QDBSTLS, QdbstListStatistics) lists all the columns and
combination of columns for a given file member that have statistics available.
• Request Statistics Collections (QDBSTRS, QdbstRequestStatistics) allows you to
request one or more statistics collections for a given set of columns of a specific file member.
• Update Statistics Collection (QDBSTUS, QdbstUpdateStatistics) allows you to update
the attributes and to refresh the data of an existing single statistics collection
Related reference
Viewing statistics requests
You can view the current statistics requests by using System i Navigator or by using Statistics APIs.

Displaying materialized query table columns


You can display materialized query tables associated with another table using System i Navigator.
To display materialized query tables, follow these steps:
1. In the System i Navigator window, expand the system that you want to use.
2. Expand Databases and the database that you want to work with.
3. Expand Schemas and the schema that you want to work with.
4. Right-click a table and select Show Materialized Query Tables.

Table 53. Columns used in Show materialized query table window


Column name Description
Name The SQL name for the materialized query table
Schema Schema or library containing the materialized query table
Partition Partition detail for the index. Possible values:
• <blank>, which means For all partitions
• For Each Partition
• specific name of the partition

Owner The user ID of the owner of the materialized query table.

Database performance and query optimization 255


Table 53. Columns used in Show materialized query table window (continued)
Column name Description
System Name System table name for the materialized query table
Enabled Whether the materialized query table is enabled. Possible
values are:
• Yes
• No
If the materialized query table is not enabled, it cannot be
used for query optimization. It can, however, be queried
directly.
Creation Date The timestamp of when the materialized table was created.
Last Refresh Date The timestamp of the last time the materialized query table
was refreshed.
Last Query Use The timestamp when the materialized query table was last
used by the optimizer to replace user specified tables in a
query.
Last Query Statistics Use The timestamp when the materialized query table was last
used by the statistics manager to determine an access
method.
Query Use Count The number of instances the materialized query table was
used by the optimizer to replace user specified tables in a
query.
Query Statistics Use Count The number of instances the materialized query table was
used by the statistics manager to determine an access
method.
Last Used Date The timestamp when the materialized query table was last
used.
Days Used Count The number of days the materialized query table has been
used.
Date Reset Days Used Count The year and date when the days-used count was last set to
0.
Current Number of Rows The total number of rows included in this materialized query
table at this time.
Current Size The current size of the materialized query table.
Last Changed The timestamp when the materialized query table was last
changed.
Maintenance The maintenance for the materialized query table. Possible
values are:
• User
• System

Initial Data Whether the initial data was inserted immediately or


deferred. Possible values are
• Deferred
• Immediate

256 IBM i: Performance and Query Optimization


Table 53. Columns used in Show materialized query table window (continued)
Column name Description
Refresh Mode The refresh mode for the materialized query table. A
materialized query table can be refreshed whenever a change
is made to the table or deferred to a later time.
Isolation Level The isolation level for the materialized query table.
Sort Sequence The alternate character sorting sequence for National
Language Support (NLS).
Language Identifier The language code for the object.
SQL Statement The SQL statement that is used to populate the table.
Text The text description of the materialized query table.
Table Schema and table name.
Table Partition Table partition.
Table System Name System name of the table.

Managing check pending constraints columns


You can view and change constraints that have been placed in a check pending state by the system. Check
pending constraints refers to a state in which a mismatch exists between a parent and foreign key in a
referential constraint. A mismatch can also occur between the column value and the check constraint
definition in a check constraint.
To view constraints that have been placed in a check pending state, follow these steps:
1. Expand the system name and Databases.
2. Expand the database that you want to work with.
3. Expand the Database Maintenance folder.
4. Select Check Pending Constraints.
5. From this interface, you can view the definition of the constraint and the rows that are in violation
of the constraint rules. Select the constraint that you want to work with and then select Edit Check
Pending Constraint from the File menu.
6. You can either alter or delete the rows that are in violation.

Table 54. Columns used in Check pending constraints window


Column name Description
Name of Constraint in Check Pending Displays the name of the constraint that is in a check pending
state.
Schema Schema containing the constraint that is in a check pending
state.
Type Displays the type of constraint that is in check pending.
Possible values are:
Check constraint
Foreign key constraint

Table name The name of the table associated with the constraint in
check pending state.

Database performance and query optimization 257


Table 54. Columns used in Check pending constraints window (continued)
Column name Description
Enabled Displays whether the constraint is enabled. The constraint
must be disabled or the relationship taken out of the check
pending state before any input/output (I/O) operations can
be performed.

Limiting temporary storage and CPU used by queries


Follow these recommendations to limit temporary storage and CPU usage.
You can prevent the query optimizer from using excessive temporary storage when running a query by
setting the maximum temporary storage parameter for jobs on your system. The maximum temporary
storage parameter (MAXTMPSTG) can be assigned to a class of jobs or it can be set for an individual
job. The parameter, defined in megabytes, limits the amount of temporary storage that a job may
allocate while it is running. The default value is *NOMAX, meaning no limit is placed on the temporary
storage. See the Change Job (CHGJOB) command for more information: https://www.ibm.com/support/
knowledgecenter/ssw_ibm_i_74/cl/chgjob.htm#CHGJOB.MAXTMPSTG
Temporary storage can be allocated by application code, by the optimizer, or by other parts of the
operating system. If the total temporary storage currently allocated by the job exceeds the maximum,
the job is held and a CPI112E message, "Job & held by the system, MAXTMPSTG limit
exceeded." is sent to the job log and to the QSYSOPR message queue. The job remains held until
the maximum is increased or removed and the job is released, or until the job is ended. Note that with
respect to the maximum temporary storage limit, only temporary storage newly allocated by the optimizer
for the currently running query is counted. If a query plan is reused from the plan cache, any associated
temporary storage will not be counted against the limit. Likewise, once the query has completed, the
optimizer's temporary storage is no longer counted against the limit, even if the cached plan and its
associated runtime objects continue to remain allocated.
Consider the following example for a job with MAXTMPSTG set to 100 MB:
1. Query 1 is submitted, is optimized, and allocates 60 MB of temporary storage. When the query is done,
the plan and its temporary storage are cached.
2. Query 2 is submitted, is optimized, and allocates 50 MB of temporary storage. When the query is done,
the plan and its temporary storage are cached. Total temporary storage usage has increased by 110
MB, but no single query has exceeded 100 MB, so the job continues to run.
3. Query 3 is submitted, and a matching plan produced from a previous run is found. This plan uses
temporary objects totaling 150 MB. However, because this job is not newly allocating the temporary
storage, MAXTMPSTG is not exceeded.
4. Query 4 is submitted, is optimized, and allocates 200 MB of temporary storage. MAXTMPSTG is
exceeded and the job is held.
In a similar manner, the Maximum CPU time (CPUTIME) parameter may be used to prevent jobs from
utilizing excessive amounts of CPU. The limit is specified in the number of milliseconds of CPU time that a
job may consume. As with MAXTMPSTG, exceeding the limit will cause the job to be held until the limit is
changed or the job is ended.
Related limits on temporary storage and running time are also available on the Change Query Attributes
(CHGQRYA) https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_74/cl/chgqrya.htm command.
Query processing time limit (QRYTIMLMT) can be used to prevent the optimizer from running queries that
are expected to take a long time, whereas QRYSTGLMT can prevent the optimizer from running queries
that are expected to use a large amount of temporary storage. Note that these differ from MAXTMPSTG
and CPUTIME in that they apply to each query individually and are based on estimates calculated by the
optimizer before the query runs. By contrast, the job-based limits apply to the actual resource usage
measured as the job runs.

258 IBM i: Performance and Query Optimization


Creating an index strategy
Db2 for i provides two basic means for accessing tables: a table scan and an index-based retrieval.
Index-based retrieval is typically more efficient than table scan when less than 20% of the table rows are
selected.
There are two kinds of persistent indexes: binary radix tree indexes, which have been available since
1988, and encoded vector indexes (EVIs). Both types of indexes are useful in improving performance for
certain kinds of queries.

Binary radix indexes


A radix index is a multilevel, hybrid tree structure that allows many key values to be stored efficiently
while minimizing access times. A key compression algorithm assists in this process. The lowest level of
the tree contains the leaf nodes, which contain the base table row addresses associated with the key
value. The key value is used to quickly navigate to the leaf node with a few simple binary search tests.
The binary radix tree structure is good for finding a few rows because it finds a given row with a minimal
amount of processing. For example, create a binary radix index over a customer number column. Then
create a typical OLTP request like "find the outstanding orders for a single customer". The binary index
results in fast performance. An index created over the customer number column is considered the perfect
index for this type of query. The index allows the database to find the rows it needs and perform a minimal
number of I/Os.
In some situations, however, you do not always have the same level of predictability. Many users want on
demand access to the detail data. For example, they might run a report every week to look at sales data.
Then they want to "drill down" for more information related to a particular problem area they found in the
report. In this scenario, you cannot write all the queries in advance on behalf of the end users. Without
knowing what queries might run, it is impossible to build the perfect index.
Related information
SQL Create Index statement

Derived key index


You can use the SQL CREATE INDEX statement to create a derived key index using an SQL expression.
Traditionally an index could only specify column names in the key of the index over the table it was based
on. With this support, an index can have an expression in place of a column name that can use built-in
functions, or some other valid expression. Additionally, you can use the SQL CREATE INDEX statement to
create a sparse index using a WHERE condition.
For restrictions and other information about derived indexes, see the Create Index statement and Using
derived indexes.
Related reference
Using derived indexes
SQL indexes can be created where the key is specified as an expression. This type of key is also referred
to as a derived key.
Related information
SQL Create Index statement

Sparse indexes
You can use the SQL CREATE INDEX statement to create a sparse index using SQL selection predicates.
The SQL CREATE INDEX statement can be used to create a sparse index using a WHERE condition. With
this support, the query optimizer recognizes and considers sparse indexes during its optimization. If the
query WHERE selection is a subset of the sparse index WHERE selection, then the sparse index is used to
implement the query. Use of the sparse index usually results in improved performance.

Database performance and query optimization 259


Examples
In this example, the query selection is a subset of the sparse index selection and an index scan over the
sparse index is used. The remaining query selection (COL3=30) is executed following the index scan.

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

In this example, the query selection is not a subset of the sparse index selection and the sparse index
cannot be used.

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20 and COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20

Related reference
Using sparse indexes
SQL indexes can be created using WHERE selection predicates. These indexes can also be referred to as
sparse indexes. The advantage of a sparse index is that fewer entries are maintained in the index. Only
those entries matching the WHERE selection criteria are maintained in the index.
Related information
SQL Create Index statement

Sparse index optimization


An SQL sparse index is like a select/omit access path. Both the sparse index and the select/omit logical
file contain only keys that meet the selection specified. For a sparse index, the selection is specified
with a WHERE clause. For a select/omit logical file, the selection is specified in the DDS using the COMP
operation.
The reason for creating a sparse index is to provide performance enhancements for your queries. The
performance enhancement is done by precomputing and storing results of the WHERE selection in the
sparse index. The database engine can use these results instead of recomputing them for a user specified
query. The query optimizer looks for any applicable sparse index and can choose to implement the query
using a sparse index. The decision is based on whether using a sparse index is a faster implementation
choice.
For a sparse index to be used, the WHERE selection in the query must be a subset of the WHERE selection
in the sparse index. That is, the set of records in the sparse index must contain all the records to be
selected by the query. It might contain extra records, but it must contain all the records to be selected by
the query. This comparison of WHERE selection is performed by the query optimizer during optimization.
It is like the comparison that is performed for Materialized Query Tables (MQT).
Besides the comparison of the WHERE selection, the optimization of a sparse index is identical to the
optimization that is performed for any Binary Radix index.
Refer to section 'Indexes and the Optimizer' for more details on how Binary Radix indexes are optimized.
Related concepts
Indexes & the optimizer
Since the optimizer uses cost based optimization, more information about the database rows and
columns makes for a more efficient access plan created for the query. With the information from the

260 IBM i: Performance and Query Optimization


indexes, the optimizer can make better choices about how to process the request (local selection, joins,
grouping, and ordering).
Related reference
Using sparse indexes
SQL indexes can be created using WHERE selection predicates. These indexes can also be referred to as
sparse indexes. The advantage of a sparse index is that fewer entries are maintained in the index. Only
those entries matching the WHERE selection criteria are maintained in the index.

Sparse index matching algorithm


This topic is a generalized discussion of how the sparse index matching algorithm works.
The selection in the query must be a subset of the selection in the sparse index in order for the sparse
index to be used. This statement is true whether the selection is ANDed together, ORed together, or
a combination of the two. For selection where all predicates are ANDed together, all WHERE selection
predicates specified in the sparse index must also be specified in the query. The query can contain
additional ANDed predicates. The selection for the additional predicates will be performed after the
entries are retrieved from the sparse index. See examples A1, A2, and A3 following.
Example A1
In this example, the query selection exactly matches the sparse index selection and an index scan over
the sparse index can be used.

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20 and COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

Example A2
In this example, the query selection is a subset of the sparse index selection and an index scan over the
sparse index can be used. The remaining query selection (COL3=30) is executed following the index scan.

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

Example A3
In this example, the query selection is not a subset of the sparse index selection and the sparse index
cannot be used.

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20 and COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20

For selection where all predicates are ORed together, all WHERE selection predicates specified in
the query, must also be specified in the sparse index. The sparse index can contain additional ORed
predicates. All the ORed selection in the query will be executed after the entries are retrieved from the
sparse index. See examples O1, O2, andO3 following.
Example O1
In this example, the query selection exactly matches the sparse index selection and an index scan over
the sparse index can be used. The query selection is executed following the index scan.

Database performance and query optimization 261


CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)
WHERE COL1=10 or COL2=20 or COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 or COL2=20 or COL3=30

Example O2
In this example, the query selection is a subset of the sparse index selection and an index scan over the
sparse index can be used. The query selection is executed following the index scan.

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 or COL2=20 or COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 or COL2=20

Example O3
In this example, the query selection is not a subset of the sparse index selection and the sparse index
cannot be used.

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 or COL2=20

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 or COL2=20 or COL3=30

The previous examples used simple selection, all ANDed, or all ORed together. These examples are
not typical, but they demonstrate how the selection of the sparse index is compared to the selection
of the query. Obviously, the more complex the selection the more difficult it becomes to determine
compatibility.
In the next example T1, the constant 'MN' was replaced by a parameter marker for the query selection.
The sparse index had the local selection of COL1='MN' applied to it when it was created. The sparse index
matching algorithm matches the parameter marker to the constant 'MN' in the query predicate COL1 =?. It
verifies that the value of the parameter marker is the same as the constant in the sparse index; therefore
the sparse index can be used.
The sparse index matching algorithm attempts to match where the predicates between the sparse index
and the query are not the same. An example is a sparse index with a predicate SALARY > 50000, and
a query with the predicate SALARY > 70000. The sparse index contains the rows necessary to run the
query. The sparse index is used in the query, but the predicate SALARY > 70000 remains as selection in
the query (it is not removed).
Example T1

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1='MN' or COL2='TWINS'

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=? or COL2='TWINS' or COL3='WIN'

In the next example T2, the keys of the sparse index match the ORDER BY fields in the query. For the
sparse index to satisfy the specified ordering, the optimizer must verify that the query selection is a
subset of the sparse index selection. In this example, the sparse index can be used.
Example T2

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL1, COL3)


WHERE COL1='MN' or COL2='TWINS'

262 IBM i: Performance and Query Optimization


SELECT COL1, COL2, COL3, COL4
FROM MYLIB/T1
WHERE COL2='TWINS'
ORDER BY COL1, COL3

Related reference
Using sparse indexes
SQL indexes can be created using WHERE selection predicates. These indexes can also be referred to as
sparse indexes. The advantage of a sparse index is that fewer entries are maintained in the index. Only
those entries matching the WHERE selection criteria are maintained in the index.
Details on the MQT matching algorithm
What follows is a generalized discussion of how the MQT matching algorithm works.

Sparse index examples


This topic shows examples of how the sparse index matching algorithm works.
In example S1, the query selection is a subset of the sparse index selection and consequently an index
scan over the sparse index is used. The remaining query selection (COL3=30) is executed following the
index scan.
Example S1

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

In example S2, the query selection is not a subset of the sparse index selection and the sparse index
cannot be used.
Example S2

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20 and COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20

In example S3, the query selection exactly matches the sparse index selection and an index scan over the
sparse index can be used.
Example S3

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20 and COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

In example S4, the query selection is a subset of the sparse index selection and an index scan over the
sparse index can be used. The remaining query selection (COL3=30) is executed following the index scan.
Example S4

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

Database performance and query optimization 263


In example S5, the query selection is not a subset of the sparse index selection and the sparse index
cannot be used.
Example S5

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20 and COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20

In example S6, the query selection exactly matches the sparse index selection and an index scan over the
sparse index can be used. The query selection is executed following the index scan to eliminate excess
records from the sparse index.
Example S6

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 or COL2=20 or COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 or COL2=20 or COL3=30

In example S7, the query selection is a subset of the sparse index selection and an index scan over the
sparse index can be used. The query selection is executed following the index scan to eliminate excess
records from the sparse index.
Example S7

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 or COL2=20 or COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 or COL2=20

In example S8, the query selection is not a subset of the sparse index selection and the sparse index
cannot be used.
Example S8

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 or COL2=20

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 or COL2=20 or COL3=30

In the next example S9, the constant 'MN' was replaced by a parameter marker for the query selection.
The sparse index had the local selection of COL1='MN' applied to it when it was created. The sparse index
matching algorithm matches the parameter marker to the constant 'MN' in the query predicate COL1 =?. It
verifies that the value of the parameter marker is the same as the constant in the sparse index; therefore
the sparse index can be used.
Example S9

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1='MN' or COL2='TWINS'

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
Where Col3='WIN' and (Col1=? or Col2='TWINS')

264 IBM i: Performance and Query Optimization


In the next example S10, the keys of the sparse index match the order by fields in the query. For the
sparse index to satisfy the specified ordering, the optimizer must verify that the query selection is a
subset of the sparse index selection. In this example, the sparse index can be used.
Example S10

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL1, COL3)


WHERE COL1='MN' or COL2='TWINS'

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
Where Col3='WIN' and (Col1='MN' or Col2='TWINS')
ORDER BY COL1, COL3

In the next example S11, the keys of the sparse index do not match the order by fields in the query. But
the selection in sparse index T2 is a superset of the query selection. Depending on size, the optimizer
might choose an index scan over sparse index T2 and then use a sort to satisfy the specified ordering.
Example S11

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL2, COL4)


WHERE COL1='MN' or COL2='TWINS'

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
Where Col3='WIN' and (Col1='MN' or Col2='TWINS')
ORDER BY COL1, COL3

The next example S12 represents the classic optimizer decision: is it better to do an index probe using
index IX1 or is it better to do an index scan using sparse index SPR1? Both indexes retrieve the same
number of index entries and have the same cost from that point forward. For example, both indexes have
the same cost to retrieve the selected records from the dataspace, based on the retrieved entries/keys.
The cost to retrieve the index entries is the deciding criteria. In general, if index IX1 is large then an index
scan over sparse index SPR1 has a lower cost to retrieve the index entries. If index IX1 is rather small
then an index probe over index IX1 has a lower cost to retrieve the index entries. Another cost decision
is reusability. The plan using sparse index SPR1 is not as reusable as the plan using index IX1 because of
the static selection built into the sparse selection.
Example S12

CREATE INDEX MYLIB/IX1 on MYLIB/T1 (COL1, COL2, COL3)

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20 and COL3=30

CSELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

Specify PAGESIZE on index creates


You can use the PAGESIZE parameter to specify the access path logical page size used by the system
when the access path is created. Use the PAGESIZE parameter when creating keyed files or indexes using
the Create Physical File (CRTPF) or Create Logical File (CRTLF) commands, or the SQL
CREATE INDEX statement.
The logical page size is the access path number of bytes that can be moved from auxiliary storage to the
job storage pool for a page fault.
Consider using the default of *KEYLEN for this parameter, except in rare circumstances. Then the page
size can be determined by the system based on the total length of the keys. When the access path is used
by selective queries (for example, individual key lookup), a smaller page size is typically more efficient.

Database performance and query optimization 265


When the query-selected keys are grouped in the access path with many records selected, or the access
path is scanned, a larger page size is more efficient.
Related information
Create Logical File (CRTLF) command
Create Physical File (CRTPF) command
SQL Create Index statement

General index maintenance


Whenever indexes are created and used, there is a potential for a decrease in I/O velocity due to
maintenance. Therefore, consider the maintenance cost of creating and using additional indexes. For radix
indexes with MAINT(*IMMED), maintenance occurs when inserting, updating, or deleting rows.
To reduce the maintenance of your indexes consider:
• Minimizing the number of table indexes by creating composite (multiple column) key indexes.
Composite indexes can be used for multiple different situations.
• Dropping indexes during batch inserts, updates, and deletes
• Creating in parallel. Either create indexes, one at a time, in parallel using SMP or create multiple indexes
simultaneously with multiple batch jobs
• Maintaining indexes in parallel using SMP
The goal of creating indexes is to improve query performance by providing statistics and implementation
choices. Maintain a reasonable balance on the number of indexes to limit maintenance overhead.

Encoded vector indexes


An encoded vector index (EVI) is used to provide fast data access in decision support and query reporting
environments.
EVIs are a complementary alternative to existing index objects (binary radix tree structure - logical file or
SQL index) and are a variation on bitmap indexing. Because of their compact size and relative simplicity,
EVIs provide for faster scans of a table that can also be processed in parallel.
An EVI is a data structure that is stored as two components:
• The symbol table contains statistical and descriptive information about each distinct key value
represented in the table. Each distinct key is assigned a unique code, either 1 byte, 2 bytes or 4 bytes in
size.
By specifying INCLUDE on the create, additional aggregate values can be maintained in real time as an
extension of the key portion of the symbol table entry. These aggregated values are over non-key data in
the table grouped by the specified EVI key.
• The vector is an array of codes listed in the same ordinal position as the rows in the table. The vector
does not contain any pointers to the actual rows in the table.
Advantages of EVIs:
• Require less storage
• May have better build times than radix, especially if the number of unique values in the columns defined
for the key is relatively small.
• Provide more accurate statistics to the query optimizer
• Considerably better performance for certain grouping types of queries
• Good performance characteristics for decision support environments.
• Can be further extended for certain types of grouping queries with the addition of INCLUDE values.
Provides ready-made numeric aggregate values maintained in real time as part of index maintenance.
INCLUDE values become an extension of the EVI symbol table. Multiple include values can be specified

266 IBM i: Performance and Query Optimization


over different aggregating columns and maintained in the same EVI provided the group by values are
the same. This technique can reduce overall maintenance.
Disadvantages of EVIs:
• Cannot be used in ordering.
• Use for grouping is specialized. Supports:
– COUNT, DISTINCT requests over key columns
– aggregate requests over key columns where all other selection can be applied to the EVI symbol table
keys
– INCLUDE aggregates
– MIN or MAX, if aggregating value is part of the symbol table key.
• Use with joins always done in cooperation with hash table processing.
• Some additional maintenance idiosyncrasies.
Related reference
Encoded vector index
An encoded vector index is a permanent object that provides access to a table. This access is done by
assigning codes to distinct key values and then representing those values in a vector.
Related information
SQL Create Index statement

How the EVI works


EVIs work in different ways for costing and implementation.
For costing, the optimizer uses the symbol table to collect metadata information about the query.
For implementation, the optimizer can use the EVI in one of the following ways:
• Selection (WHERE clause)
The database engine uses the vector to build a dynamic bitmap or list of selected row ids. The bitmap
or list contains 1 bit for each row in the table. The bit is turned on for each selected row. Like a bitmap
index, these intermediate dynamic bitmaps (or lists) can be ANDed and ORed together to satisfy a
query.
For example, a user wants to see sales data for a specific region and time period. You can define an EVI
over the region and quarter columns of the table. When the query runs, the database engine builds
dynamic bitmaps using the two EVIs. The bitmaps are ANDed together to produce a single bitmap
containing only the relevant rows for both selection criteria.
This ANDing capability drastically reduces the number of rows that the system must read and test.
The dynamic bitmaps exists only as long as the query is executing. Once the query is completed, the
dynamic bitmaps are eliminated.
• Grouping or Distinct
The symbol table within the EVI contains distinct values for the specified columns in the key definition.
The symbol table also contains a count of the number of records in the base table that have each
distinct value. Queries involving grouping or distinct, based solely on columns in the key, are candidates
for a technique that uses the symbol table directly to determine the query result.
The symbol table contains only the key values and their associated counts, unless INCLUDE is specified.
Therefore, queries involving column function COUNT are eligible for this technique. But queries with
column functions MIN or MAX on other non-key columns are not eligible. MIN and MAX values are not
stored in the symbol table.
• EVI INCLUDE aggregates

Database performance and query optimization 267


Including additional aggregate values further extends the ability of the symbol table to provide ready-
made results. Aggregate data is grouped by the specified columns in the key definition. Therefore,
aggregate data must be over columns in the table other than those columns specified as EVI key values.
For performance, these included aggregates are limited to numeric results (SUM, COUNT, AVG,
VARIANCE) as they can be maintained directly from the inserted or removed row.
MIN or MAX values would occasionally require other row comparisons during maintenance and
therefore are not supported with the INCLUDE keyword.
EVI symbol table only access is used to satisfy distinct or grouping requests when the query is run with
commitment control *NONE or *CHG.
INCLUDE for additional aggregate values can be used in join queries. When possible, the existence
of EVIs with INCLUDE aggregates causes the group by process to be pushed down to each table as
necessary. See the following EVI INCLUDE grouping push down example: “EVI INCLUDE aggregate
example” on page 82
Related reference
Encoded vector index index-symbol table only access
The encoded vector index can also be used for index-symbol table only access.
Encoded vector index symbol table scan
An encoded vector index symbol table scan operation is used to retrieve the entries from the symbol table
portion of the index.
Encoded vector index symbol table probe
An encoded vector index symbol table probe operation is used to retrieve entries from the symbol table
portion of the index. Scanning the entire symbol table is not necessary.
Index grouping implementation
There are two primary ways to implement grouping using an index: Ordered grouping and pre-
summarized processing.

When to create EVIs


There are several instances to consider creating EVIs.
Consider creating encoded vector indexes when any one of the following is true:
• You want to gather 'live' statistics
• Full table scan is currently being selected for the query
• Selectivity of the query is 20%-70% and using skip sequential access with dynamic bitmaps speed up
the scan
• When a star schema join is expected to be used for star schema join queries.
• When grouping or distinct queries are specified against a column, the columns have few distinct values
and only the COUNT column function, if any, is used.
• When ready-made aggregate results grouped by the specified key columns would benefit query
performance.
Create encoded vector indexes with:
• Single key columns with a low number of distinct values expected
• Keys columns with a low volatility (do not change often)
• Maximum number of distinct values expected using the WITH n DISTINCT VALUES clause
• Single key over foreign key columns for a star schema model

EVI with INCLUDE vs Materialized Query Tables


Although EVIs with INCLUDE are not a substitute for Materialized Query Tables (MQTs), INCLUDE EVIs
have an advantage over single table aggregate MQTs (materialized query tables). The advantage is that

268 IBM i: Performance and Query Optimization


the ready-made aggregate results are maintained in real time, not requiring explicit REFRESH TABLE
requests. For performance and read access to aggregate results, consider turning your single table,
aggregate MQTs into INCLUDE EVIs. Keep in mind that the other characteristics of a good EVI are
applicable, such as a relatively low number of distinct key values.
As indexes, these EVIs are found during optimization just as any other indexes are found. Unlike MQTs,
there is no INI setting to enable and no second pass through the optimizer to cost the application of this
form of ready-made aggregate. In addition, EVIs with INCLUDE can be used to populate MQT summary
tables if the EVI is a match for a portion of the MQT definition.
Related reference
Encoded vector index symbol table scan
An encoded vector index symbol table scan operation is used to retrieve the entries from the symbol table
portion of the index.
Index grouping implementation

Database performance and query optimization 269


There are two primary ways to implement grouping using an index: Ordered grouping and pre-
summarized processing.

EVI maintenance
There are unique challenges to maintaining EVIs. The following table shows a progression of how EVIs are
maintained, the conditions under which EVIs are most effective, and where EVIs are least effective, based
on the EVI maintenance characteristics.

270 IBM i: Performance and Query Optimization


Table 55. EVI Maintenance Considerations
Condition Characteristics
When inserting an existing • Minimum overhead
distinct key value
• Symbol table key value looked up and statistics updated
Most Effective
• Vector element added for new row, with existing byte
code
• Minimal additional pathlength to maintain any INCLUDEd
aggregate values (the increment of a COUNT or adding to
an accumulating SUM)

When inserting a new distinct • Minimum overhead


key value - in order, within byte
• Symbol table key value added, byte code assigned,
code range
statistics assigned
• Vector element added for new row, with new byte code
• Minimal additional pathlength to maintain any INCLUDEd
aggregate values (the increment of a COUNT or adding to
an accumulating SUM)

When inserting a new distinct • Minimum overhead if contained within overflow area
key value - out of order, within threshold
byte code range
• Symbol table key value added to overflow area, byte code
assigned, statistics assigned
• Vector element added for new row, with new byte code
• Considerable overhead if overflow area threshold reached
• Access path validated - not available
• EVI refreshed, overflow area keys incorporated, new
byte codes assigned (symbol table and vector elements
updated)
• Minimal additional path-length to maintain any INCLUDEd
aggregate values (the increment of a COUNT or adding to
an accumulating SUM)

When inserting a new distinct • Considerable overhead


key value - out of byte code
• Access plan invalidated - not available
range
• EVI refreshed, next byte code size used, new byte codes
assigned (symbol table and vector elements updated
• Not applicable to EVIs with INCLUDE, as by definition the
max allowed byte code is used

Least Effective

Related reference
Encoded vector index

Database performance and query optimization 271


An encoded vector index is a permanent object that provides access to a table. This access is done by
assigning codes to distinct key values and then representing those values in a vector.

Recommendations for EVI use


Encoded vector indexes are a powerful tool for providing fast data access in decision support and query
reporting environments. To ensure the effective use of EVIs, use the following guidelines.

Create EVIs on
• Read-only tables or tables with a minimum of INSERT, UPDATE, DELETE activity.
• Key columns that are used in the WHERE clause - local selection predicates of SQL requests.
• Single key columns that have a relatively small set of distinct values.
• Multiple key columns that result in a relatively small set of distinct values.
• Key columns that have a static or relatively static set of distinct values.
• Non-unique key columns, with many duplicates.

Create EVIs with the maximum byte code size expected


• Use the "WITH n DISTINCT VALUES" clause on the CREATE ENCODED VECTOR INDEX statement.
• If unsure, use a number greater than 65,535 to create a 4 byte code. This method avoids the EVI
maintenance involved in switching byte code sizes.
• EVIs with INCLUDE always create with a 4 byte code.

When loading data


• Drop EVIs, load data, create EVIs.
• EVI byte code size is assigned automatically based on the number of actual distinct key values found in
the table.
• Symbol table contains all key values, in order, no keys in overflow area.
• EVIs with INCLUDE always use 4 byte code

Consider adding INCLUDE values to existing EVIs


An EVI index with INCLUDE values can be used to supply ready-made aggregate results. The existing
symbol table and vector are still used for table selection, when appropriate, for skip sequential plans over
large tables, or for index ANDing and ORing plans. If you already have EVIs, consider creating new ones
with additional INCLUDE values, and then drop the pre-existing index.

Consider specifying multiple INCLUDE values on the same EVI create


If you need different aggregates over different table values for the same GROUP BY columns specified as
EVI keys, define those aggregates in the same EVI. This definition cuts down on maintenance costs and
allows for a single symbol table and vector.
For example:

Select SUM(revenue) from sales group by Country

Select SUM(costOfGoods) from sales group by Country, Region

Both queries could benefit from the following EVI:

CREATE ENCODED VECTOR INDEX eviCountryRegion on Sales(country,region)


INCLUDE(SUM(revenue), SUM(costOfGoods))

272 IBM i: Performance and Query Optimization


The optimizer does additional grouping (regrouping) if the EVI key values are wider than the
corresponding GROUP BY request of the query. This additional grouping would be the case in the first
example query.
If an aggregate request is specified over null capable results, an implicit COUNT over that same result
is included as part of the symbol table entry. The COUNT is used to facilitate index maintenance when
a requested aggregate needs to reflect. It can also assist with pushing aggregation through a join if the
optimizer determines this push is possible. The COUNT is then used to help compensate for fewer join
activity due to the pushed down grouping.

Consider EVI INCLUDE and Grouping Sets


EVI INCLUDE support has been expanded to match GROUPING SETs, ROLLUP and CUBE queries.
When EVI INCLUDES are available over a table being aggregated over in a grouping sets query, the query
is rewritten to facilitate and match any EVI INCLUDE indexes that might be available. This can result
in exceeding good query performance because the table is never accessed. All the aggregate variations
necessary to perform the rollup, cube or grouping set query result can be performed over the EVI symbol
table with INCLUDE values.
For example on the ROLLUP query below, the grouping is the sum of quantity rolled up at various levels
(month, quarter, year) and ONLY the symbol table of the encoded vector index is accessed in the access
plan.

SELECT year(shipdate) year_ship, quarter(shipdate) quarter, month(shipdate) month_ship,


sum(quantity)
as totquantity
FROM item_fact
GROUP BY ROLLUP (Year(shipdate), Quarter(shipdate), month(shipdate));

Here is the EVI INCLUDE create that will facilitate the rollup query.

CREATE ENCODED VECTOR INDEX GS_EVI


ON ITEM_FACT
( YEAR ( SHIPDATE ) ASC , QUARTER ( SHIPDATE ) ASC , MONTH ( SHIPDATE ) ASC )
INCLUDE ( SUM ( QUANTITY ) , COUNT ( * ) );

The following graphic shows a Visual Explain that illustrates the access and the performance. Instead of
accessing potentially millions of rows, the access is over a rather modest size symbol table.

Database performance and query optimization 273


Consider SMP and parallel index creation and maintenance
Symmetrical Multiprocessing (SMP) is a valuable tool for building and maintaining indexes in parallel. The
results of using the optional SMP feature of IBM i are faster index build times, and faster I/O velocities
while maintaining indexes in parallel. Using an SMP degree value of either *OPTIMIZE or *MAX, additional
multiple tasks and additional system resources are used to build or maintain the indexes. With a degree
value of *MAX, expect linear scalability on index creation. For example, creating indexes on a 4-processor
system can be four times as fast as a 1-processor system.

Checking values in the overflow area


You can also use the Display File Description (DSPFD) command (or System i Navigator -
Database) to check how many values are in the overflow area. Once the DSPFD command is issued, check
the overflow area parameter for details on the initial and actual number of distinct key values in the
overflow area.

Using CHGLF to rebuild the access path of an index


Use the Change Logical File (CHGLF) command with the attribute Force Rebuild Access Path set
to YES (FRCRBDAP(*YES)). This command accomplishes the same thing as dropping and recreating the
index, but it does not require that you know about how the index was built. This command is especially
effective for applications where the original index definitions are not available, or for refreshing the access
path.
Related information
SQL Create Index statement
Change Logical File (CHGLF) command
Display File Description (DSPFD) command

274 IBM i: Performance and Query Optimization


Comparing binary radix indexes and encoded vector indexes
Db2 for IBM i makes indexes a powerful tool.
The following table summarizes some of the differences between binary radix indexes and encoded
vector indexes:

Table 56. Comparison of radix and EVI indexes


Comparison value Binary Radix Indexes Encoded Vector Indexes
Basic data structure A wide, flat tree A Symbol Table and a vector
Interface for creating Command, SQL, System i SQL, System i Navigator
Navigator
Can be created in parallel Yes Yes
Can be maintained in parallel Yes Yes
Used for statistics Yes Yes
Used for selection Yes Yes, with dynamic bitmaps or
RRN list
Used for joining Yes Yes (with a hash table)
Used for grouping Yes Yes
Used for ordering Yes No
Used to enforce unique Yes No
Referential Integrity constraints
Source for predetermined or No Yes, with INCLUDE keyword
ready-made numeric aggregate option on create
results

Indexes & the optimizer


Since the optimizer uses cost based optimization, more information about the database rows and
columns makes for a more efficient access plan created for the query. With the information from the
indexes, the optimizer can make better choices about how to process the request (local selection, joins,
grouping, and ordering).
The CQE optimizer attempts to examine most, if not all, indexes built over a table unless or until it times
out. However, the SQE optimizer only considers those indexes that are returned by the Statistics Manager.
These include only indexes that the Statistics Manager decides are useful in performing local selection
based on the "where" clause predicates. Consequently, the SQE optimizer does not time out.
The primary goal of the optimizer is to choose an implementation that efficiently eliminates the rows that
are not interesting or required to satisfy the request. Normally, query optimization is thought of as trying
to find the rows of interest. A proper indexing strategy assists the optimizer and database engine with this
task.

Instances where an index is not used


Db2 for i does not use indexes in the certain instances.
• For a column that is expected to be updated; for example, when using SQL, your program might include
the following:

EXEC SQL
DECLARE DEPTEMP CURSOR FOR
SELECT EMPNO, LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
WHERE (WORKDEPT = 'D11' OR

Database performance and query optimization 275


WORKDEPT = 'D21') AND
EMPNO = '000190'
FOR UPDATE OF EMPNO, WORKDEPT
END-EXEC.

When using the OPNQRYF command, for example:

OPNQRYF FILE((CORPDATA/EMPLOYEE)) OPTION(*ALL)


QRYSLT('(WORKDEPT *EQ ''D11'' *OR WORKDEPT *EQ ''D21'')
*AND EMPNO *EQ ''000190''')

Even if you do not intend to update the employee department, the system cannot use an index with a
key of WORKDEPT.
An index can be used if all the index updatable columns are also used within the query as an isolatable
selection predicate with an equal operator. In the previous example, the system uses an index with a
key of EMPNO.
The system can operate more efficiently if the FOR UPDATE OF column list only names the column you
intend to update: WORKDEPT. Therefore, do not specify a column in the FOR UPDATE OF column list
unless you intend to update the column.
If you have an updatable cursor because of dynamic SQL, or FOR UPDATE was not specified and the
program contains an UPDATE statement, then all columns can be updated.
• For a column being compared with another column from the same row. For example, when using SQL,
your program might include the following:

EXEC SQL
DECLARE DEPTDATA CURSOR FOR
SELECT WORKDEPT, DEPTNAME
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = ADMRDEPT
END-EXEC.

When using the OPNQRYF command, for example:

OPNQRYF FILE (EMPLOYEE) FORMAT(FORMAT1)


QRYSLT('WORKDEPT *EQ ADMRDEPT')

Even though there is an index for WORKDEPT and another index for ADMRDEPT, Db2 for i does not use
either index. The index has no added benefit because every row of the table needs to be looked at.

Display indexes for a table


You can display indexes that are created on a table using System i Navigator.
To display indexes for a table, follow these steps:
1. In the System i Navigator window, expand the system that you want to use.
2. Expand Databases and the database that you want to work with.
3. Expand Schemas and the schema that you want to work with.
4. Right-click a table and select Show Indexes.
The Show index window includes the following columns:

Table 57. Columns used in Show index window


Column name Description
Name The SQL name for the index

276 IBM i: Performance and Query Optimization


Table 57. Columns used in Show index window (continued)
Column name Description
Type The type of index displayed. Possible values are:
• Keyed Physical File
• Keyed Logical File
• Primary Key Constraint
• Unique Key Constraint
• Foreign Key Constraint
• Index

Schema Schema or library containing the index or access path


Owner User ID of the owner of this index or access path
System Name System table name for the index or access path.
Text The text description of the index or access path
Index partition Partition detail for the index. Possible values:
• <blank>, For all partitions
• For Each Partition
• specific name of the partition

Valid Whether the access path or index is valid. The possible


values are Yes or No.
Creation Date The timestamp of when the index was created.
Last Build The last time that the access path or index was rebuilt.
Last Query Use Timestamp when the access path was last used by the
optimizer.
Last Query Statistics Use Timestamp when the access path was last used for statistics
Query Use Count Number of times the access path has been used for a query
Query Statistics Use Count Number of times the access path has been used for statistics
Last Used Date Timestamp when the access path or index was last used.
Days Used Count The number of days the index has been used.
Date Reset Days Used Count The year and date when the days-used count was last set to
0.
Number of Key Columns The number of key columns defined for the access path or
index.
Key Columns The key columns defined for the access path or index.
Current Key Values The number of current key values.
Current Size The size of the access path or index.
Current Allocated Pages The current number of pages allocated for the access path or
index.

Database performance and query optimization 277


Table 57. Columns used in Show index window (continued)
Column name Description
Logical Page Size The number of bytes used for the access path or the
logical page size of the index. Indexes with larger logical
page sizes are typically more efficient when scanned during
query processing. Indexes with smaller logical page sizes
are typically more efficient for simple index probes and
individual key look ups. If the access path or index is an
encoded vector, the value 0 is returned.
Duplicate Key Order How the access path or index handles duplicate key values.
Possible values are:
• Unique - all values are unique.
• Unique where not null - all values are unique unless null is
specified.

Maximum Key Length The maximum key length for the access path or index.
Unique Partial Key Values The number of unique partial keys for the key fields 1
through 4. If the access path is an encoded vector, this
number represents the number of full key distinct values.
Overflow Values The number of overflow values for this encoded vector index.
Key Code Size The length of the code assigned to each distinct key value of
the encoded vector index.
Sparse Is the index considered sparse. Sparse indexes only contain
keys for rows that satisfy the query. Possible values are:
• Yes
• No

Derived Key Is the index considered derived. A derived key is a key that
is the result of an operation on the base column. Possible
values are:
• Yes
• No

Partitioned Is the index partition created for each data partition defined
for the table using the specified columns. Possible values
are:
• Yes
• No

Maximum Size The maximum size of the access path or index.


Sort Sequence The alternate character sorting sequence for National
Language Support (NLS).
Language Identifier The language code for the object.
Estimated Rebuild Time The estimated time in seconds required to rebuild the access
path or index.

278 IBM i: Performance and Query Optimization


Table 57. Columns used in Show index window (continued)
Column name Description
Held Is a rebuild of an access path or index held. Possible values
are:
• Yes
• No

Maintenance For objects with key fields or join logical files, the type of
access path maintenance used. The possible values are:
• Do not wait
• Delayed
• Rebuild

Delayed Maintenance Keys The number of delayed maintenance keys for the access
path or index.
Recovery When the access path is rebuilt after damage to the access
path is recognized. The possible values are:
• After IPL
• During IPL
• Next Open

Index Logical Reads The number of access path or index logical read operations
since the last IPL.
WHERE Clause Specifies the condition to apply for a row to be included in
the index.
WHERE Clause Has UDF Does the WHERE clause have a UDF. Possible values are:
• Yes
• No

Table Table name of the table that the index is based on.
Table Partition Partition name of the table that the index is based on.
Table System Name System name of the table that the index is based on.
Last Rebuild Number Keys Number of keys in the index when the index was last rebuilt.
Last Rebuild Parallel Degree Parallel degree used when the index was last rebuilt.
Last Rebuild Time Amount of time in seconds it took to rebuild the index the
last time the index was rebuilt.
Keep in Memory Is the index kept in memory. Possible values are:
• Yes
• No

Sort Sequence Schema Schema of the sort sequence table if one is used.
Sort Sequence Name Name of the sort sequence table if one is used.
Random Reads The number of reads that have occurred in a random fashion.
Random means that the location of the row or key could not
be predicted ahead of time.

Database performance and query optimization 279


Table 57. Columns used in Show index window (continued)
Column name Description
Media Preference Indicates preference whether the storage for the table,
partition, or index is allocated on Solid State Disk (SSD), if
available.

Determine unnecessary indexes


You can easily determine which indexes are being used for query optimization.
Before V5R3, it was difficult to determine unnecessary indexes. Using the Last Used Date was not
dependable, as it was only updated when the logical file was opened using a native database application
(for example, an RPG application). Furthermore, it was difficult to find all the indexes over a physical
file. Indexes are created as part of a keyed physical file, keyed logical file, join logical file, SQL index,
primary key or unique constraint, or referential constraint. However, you can now easily find all indexes
and retrieve statistics on index usage as a result of System i Navigator and IBM i functionality. To assist
you in tuning your performance, this function now produces statistics on index usage as well as index
usage in a query.
To access index information through the System i Navigator, navigate to: Database > Schemas > Tables.
Right-click your table and select Show Indexes.
You can show all indexes for a schema by right-clicking on Tables or Indexes and selecting Show indexes.
Note: You can also view the statistics through the Retrieve Member Description (QUSRMBRD) API.
Certain fields available in the Show Indexes window can help you to determine any unnecessary indexes.
Those fields are:

Last Query Use States the timestamp when the index was last used to retrieve data for a
query.
Last Query Statistic Use States the timestamp when the index was last used to provide statistical
information.
Query Use Count Lists the number of instances the index was used in a query.
Query Statistics Use Lists the number of instances the index was used for statistical information.
Last Used Date The century and date this index was last used.
Days Used Count The number of days the index was used. If the index does not have a last
used date, the count is 0.
Date Reset Days Used The date that the days used count was last reset. You can reset the days used
Count by Change Object Description (CHGOBJD) command.

The fields start and stop counting based on your situation, or the actions you are currently performing on
your system. The following list describes what might affect one or both of your counters:
• The SQE and CQE query engines increment both counters. As a result, the statistics field is updated
regardless of which query interface is used.
• A save and restore procedure does not reset the statistics counter if the index is restored over an
existing index. If an index is restored that does not exist on the system, the statistics are reset.
Related information
Retrieve Member Description (QUSRMBRD) API
Change Object Description (CHGOBJD) command

Reset usage counts


Resetting the usage counts for a table allows you to determine how the changes you made to your
indexing strategy affected the indexes and constraints on that table. For example, if your new strategy

280 IBM i: Performance and Query Optimization


causes an index to never be used, you could then delete that index. Resetting usage counts on a table
affect all indexes and constraints that are created on that object.
Note: Resetting usage counts for a keyed physical file or a constraint in the Show Indexes window resets
the counts of all constraints and keyed access for that file or table.
You can reset index usage counts by right-clicking a specific index in the Indexes folder or in the Show
Indexes dialog and selecting Reset Usage Counts.

View index build status


You can view a list of indexes that are being built by the database. This view might be helpful in
determining when the index becomes usable to your applications.
To display indexes that are being built, follow these steps:
1. In the System i Navigator window, expand the system that you want to use.
2. Expand Databases.
3. Expand the database that you want to work with and then expand the Database Maintenance folder.
Select Index Builds.

Manage index rebuilds


You can manage the rebuild of your indexes using System i Navigator. You can view a list of access paths
that are rebuilding and either hold the access path rebuild or change the priority of a rebuild.
To display access paths to rebuild, follow these steps:
1. In the System i Navigator window, expand the system that you want to use.
2. Expand Databases.
3. Expand the database that you want to work with and then expand the Database Maintenance folder.
Select Index Rebuilds.
The access paths to rebuild dialog includes the following columns:

Table 58. Columns used in Index rebuilds window


Column name Description
Name Name of access path being rebuilt.
Schema Schema name where the index is located.
System Name The system name of the file that owns the index to be rebuilt.
System Schema System schema name of access path being rebuilt.
Type The type of index displayed. Possible values are:
Keyed Physical File
Keyed Logical File
Primary Key
Unique Key
Foreign Key
Index

Database performance and query optimization 281


Table 58. Columns used in Index rebuilds window (continued)
Column name Description
Status Displays the status of the rebuild. Possible values are:
1-99 – Rebuild Priority
Running – Rebuilding
Held – Held from be rebuilt

Rebuild Priority Displays the priority in which the rebuild for this
access path is run. Also referred to as sequence
number.
Possible values are:
1-99: Order to rebuild
Held
Open

Rebuild Reason Displays the reason why this access path needs to be rebuilt.
Possible values are:
Create or build index
IPL
Runtime error
Change file or index sharing
Other
Not needed
Change End of Data
Restore
Alter table
Change table
Change file
Reorganize
Enable a constraint
Alter table recovery
Change file recovery
Index shared
Runtime error
Verify constraint
Convert member
Restore recovery

282 IBM i: Performance and Query Optimization


Table 58. Columns used in Index rebuilds window (continued)
Column name Description
Rebuild Reason Subtype Displays the subtype reason why this access path needs to
be rebuilt. Possible values are:
Unexpected error
Index in use during failure
Unexpected error during update, delete, or insert
Delayed maintenance overflow or catch-up error
Other
No event
Change End of Data
Delayed maintenance mismatch
Logical page size mismatch
Partial index restore
Index conversion
Index not saved and restored
Partitioning mismatch
Partitioning change
Index or key attributes change
Original index invalid
Index attributes change
Force rebuild of index
Index not restored
Asynchronous rebuilds requested
Job ended abnormally
Alter table
Change constraint
Index invalid or attributes change
Invalid unique index found
Invalid constraint index found
Index conversion required
If there is no subtype, this field displays 0.

Database performance and query optimization 283


Table 58. Columns used in Index rebuilds window (continued)
Column name Description
Invalidation Reason Displays the reason why this access path was invalidated.
Possible values are:
User requested (See Invalidation Reason type for
more information)
Create or build Index
Load (See Invalidation Reason type for more
information)
Initial Program Load (IPL)
Runtime error
Modify
Journal failed to build the index
Marked index as fixable during runtime
Marked index as fixable during IPL
Change end of data

284 IBM i: Performance and Query Optimization


Table 58. Columns used in Index rebuilds window (continued)
Column name Description
Invalidation Reason Type Displays the reason type for why this access path was
invalidation.

Possible reason types for User requested:


Invalid because of REORG
It is a copy
Alter file
Converting new member
Change to *FRCRBDAP
Change to *UNIQUE
Change to *REBLD

Possible reason type for LOAD


The index was marked for invalidation but the
system crashed before the invalidation could
actually occur
The index was associated with the overlaid data
space header during a load, therefore it was
invalidated
Index was in IMPI format. The header was
converted and now it is invalidated to be rebuilt
in RISC format
The RISC index was converted to V5R1 format
Index invalidated due to partial load
Index invalidated due to a delayed maintenance
mismatch
Index invalidated due to a pad key mismatch
Index invalidated due to a significant fields bitmap
fix
Index invalidated due to a logical page size
mismatch
Index was not restored. File might have been
saved with ACCPTH(*NO) or index did not exist
when file was saved.
Index was not restored. File might have been
saved with ACCPTH(*NO) or index did not exist
when file was saved.
Index was rebuilt because file was saved in an
inconsistent state with SAVACT(*SYSDFN).
For other invalidation codes, this field displays 0.
Estimated Rebuild Time Estimated amount of time in seconds that it takes to rebuild
the index access path.
Rebuild Start Time Time when the rebuild was started.

Database performance and query optimization 285


Table 58. Columns used in Index rebuilds window (continued)
Column name Description
Elapsed Rebuild Time Amount of time that has elapsed in seconds since the start of
the rebuild of the access path.
Unique Indicates whether the rows in the access path are unique.
Possible values are:
Yes
No

Last Query Use Timestamp when the access path was last used
Last Query Statistics Use Timestamp when the access path was last used for statistics
Query Use Count Number of times the access path has been used for a query
Query Statistics Use Count Number of times the access path has been used for statistics
Partition Partition detail for the index. Possible values:
• <blank>, which means For all partitions
• For Each Partition
• specific name of the partition

Owner User ID of the owner of this access path.


Parallel Degree Number of processors to be used to rebuild the index.
Text Text description of the file owning the index.

You can also use the Edit Rebuild of Access Paths (EDTRBDAP) command to manage rebuilding
of access paths.
Related information
Rebuild access paths
Edit Rebuild of Access Paths (EDTRBDAP) command

Indexing strategy
There are two approaches to index creation: proactive and reactive. Proactive index creation involves
anticipating which columns are most often used for selection, joining, grouping, and ordering. Then
building indexes over those columns. In the reactive approach, indexes are created based on optimizer
feedback, query implementation plan, and system performance measurements.
It is useful to initially build indexes based on the database model and applications and not any particular
query. As a starting point, consider designing basic indexes based on the following criteria:
• Primary and foreign key columns based on the database model
• Commonly used local selection columns, including columns that are dependent, such as an
automobile's make and model
• Commonly used join columns not considered primary or foreign key columns
• Commonly used grouping columns
Related information
Indexing and statistics strategies for DB2 for i5/OS

286 IBM i: Performance and Query Optimization


Reactive approach to tuning
To perform reactive tuning, build a prototype of the proposed application without any indexes and start
running some queries. Or you could build an initial set of indexes and start running the application to see
which ones get used and which do not. Even with a smaller database, the slow running queries become
obvious quickly.
The reactive tuning method is also used when trying to understand and tune an existing application that is
not performing up to expectations. Use the appropriate debugging and monitoring tools, described in the
next section, to view the database feedback messages:
• the indexes the optimizer recommends for local selection
• the temporary indexes used for a query
• the query implementation methods the optimizer chose
If the database engine is building temporary indexes to process joins or perform grouping and selection
over permanent tables, build permanent indexes over the same columns. This technique is used to
eliminate the temporary index creation. In some cases, a temporary index is built over a temporary table,
so a permanent index is not able to be built for those tables. You can use the optimization tools listed
in the previous section to note the temporary index creation, the reason it was created, and the key
columns.

Proactive approach to tuning


Typically you will create an index for the most selective columns and create statistics for the least
selective columns in a query. By creating an index, the optimizer knows that the column is selective and it
also gives the optimizer the ability to use that index to implement the query.
In a perfect radix index, the order of the columns is important. In fact, it can make a difference as to
whether the optimizer uses it for data retrieval at all. As a general rule, order the columns in an index in
the following way:
• Equal predicates first. That is, any predicate that uses the "=" operator may narrow down the range of
rows the fastest and should therefore be first in the index.
• If all predicates have an equal operator, then order the columns as follows:
– Selection predicates + join predicates
– Join predicates + selection predicates
– Selection predicates + group by columns
– Selection predicates + order by columns
In addition to the guidelines above, in general, the most selective key columns should be placed first in
the index.
Consider the following SQL statement:

SELECT b.col1, b.col2, a.col1


FROM table1 a, table2 b
WHERE b.col1='some_value' AND
b.col2=some_number AND
a.join_col=b.join_col
GROUP BY b.col1, b.col2, a.col1
ORDER BY b.col1

With a query like this, the proactive index creation process can begin. The basic rules are:
• Custom-build a radix index for the largest or most commonly used queries. Example using the query
above:

radix index over join column(s) - a.join_col and b.join_col


radix index over most commonly used local selection column(s) - b.col2

Database performance and query optimization 287


• For ad hoc online analytical processing (OLAP) environments or less frequently used queries, build
single-key EVIs over the local selection column(s) used in the queries. Example using the query above:

EVI over non-unique local selection columns - b.col1 and b.col2

Coding for effective indexes


The following topics provide suggestions to help you design code which allows Db2 for i to take advantage
of available indexes:

Avoid numeric conversions


When a column value and a host variable (or constant value) are being compared, try to specify the same
data types and attributes. Db2 for i might not use an index for the named column if the host variable or
constant value has a greater precision than the precision of the column. If the two items being compared
have different data types, Db2 for i needs to convert one or the other of the values, which can result in
inaccuracies (because of limited machine precision).
To avoid problems for columns and constants being compared, use the following:
• same data type
• same scale, if applicable
• same precision, if applicable
For example, EDUCLVL is a halfword integer value (SMALLINT). When using SQL, specify:

… WHERE EDUCLVL < 11 AND


EDUCLVL >= 2

instead of

… WHERE EDUCLVL < 1.1E1 AND


EDUCLVL > 1.3

When using the OPNQRYF command, specify:

... QRYSLT('EDUCLVL *LT 11 *AND ENUCLVL *GE 2')

instead of

... QRYSLT('EDUCLVL *LT 1.1E1 *AND EDUCLVL *GT 1.3')

If an index was created over the EDUCLVL column, then the optimizer might not use the index in the
second example. The constant precision is greater than the column precision. It attempts to convert the
constant to the precision of the column. In the first example, the optimizer considers using the index,
because the precisions are equal.

Avoid arithmetic expressions


Do not use an arithmetic expression as an operand to compare to a column in a row selection predicate.
The optimizer does not use an index on a column compared to an arithmetic expression. While this
technique might not cause the column index to become unusable, it prevents any estimates and possibly
the use of index scan-key positioning. The primary thing that is lost is the ability to use and extract any
statistics that might be useful in the optimization of the query.
For example, when using SQL, specify the following:

… WHERE SALARY > 16500

288 IBM i: Performance and Query Optimization


instead of

… WHERE SALARY > 15000*1.1

Avoid character string padding


Try to use the same data length when comparing a fixed-length character string column value to a host
variable or constant value. Db2 for i might not use an index if the constant value or host variable is longer
than the column length.
For example, EMPNO is CHAR(6) and DEPTNO is CHAR(3). For example, when using SQL, specify the
following:

… WHERE EMPNO > '000300' AND


DEPTNO < 'E20'

instead of

… WHERE EMPNO > '000300 ' AND


DEPTNO < 'E20 '

When using the OPNQRYF command, specify:

... QRYSLT('EMPNO *GT "000300" *AND DEPTNO *LT "E20"')

instead of

... QRYSLT('EMPNO *GT "000300" *AND DEPTNO *LT "E20"')

Avoid the use of LIKE patterns beginning with % or _


The percent (%), and underline (_), used in the pattern of a LIKE (OPNQRYF %WLDCRD) predicate, specify
a character string like the row column values to select. They can take advantage of indexes when used to
denote characters in the middle or at the end of a character string.
For example, when using SQL, specify the following:

… WHERE LASTNAME LIKE 'J%SON%'

When using the OPNQRYF command, specify the following:

... QRYSLT('LASTNAME *EQ %WLDCRD(''J*SON*'')')

However, when used at the beginning of a character string, they can prevent Db2 for i from using any
indexes that might be defined on the LASTNAME column to limit the number of rows scanned using index
scan-key positioning. Index scan-key selection, however, is allowed. For example, in the following queries
index scan-key selection can be used, but index scan-key positioning cannot.
In SQL:

… WHERE LASTNAME LIKE '%SON'

In OPNQRYF:

… QRYSLT('LASTNAME *EQ %WLDCRD(''*SON'')')

Avoid patterns with a % so that you can get the best performance with key processing on the predicate. If
possible, try to get a partial string to search so that index scan-key positioning can be used.
For example, if you were looking for the name "Smithers", but you only type "S%," this query returns all
names starting with "S." Adjust the query to return all names with "Smi%". By forcing the use of partial
strings, you might get better performance in the long term.

Database performance and query optimization 289


Using derived indexes
SQL indexes can be created where the key is specified as an expression. This type of key is also referred
to as a derived key.
Suppose the following index is defined:

CREATE INDEX TOTALIX ON EMPLOYEE(SALARY+BONUS+COMM AS TOTAL)

Now, return all the employees whose total compensation is greater than 50000.

SELECT * FROM EMPLOYEE


WHERE SALARY+BONUS+COMM > 50000
ORDER BY SALARY+BONUS+COMM

The optimizer uses the index TOTALIX with index probe to satisfy both the WHERE selection and the
ordering criteria.
There are some special considerations for matching the derived key with an expression used in the query.
• No expression matching is done to match index key constants with host variables used in a query. This
includes implicit parameter marker conversion performed by the database manager.

CREATE INDEX D_IDX1 ON EMPLOYEE (SALARY/12 AS MONTHLY)

In this example, return all employees whose monthly salary is greater than 3000. Use a host variable to
provide the value used by the query.

long months = 12;


EXEC SQL SELECT * FROM EMPLOYEE WHERE SALARY/:months > 3000

The optimizer does not use the index since there is no support for matching the host variable value
months in the query to the constant 12 in the index.
• For a dynamic SQL statement, using the QAQQINI option PARAMETER_MARKER_CONVERSION with
value *NO can be used to prevent conversion of constants to parameter markers. This technique allows
for improved derived index key matching. However, because of the performance implications of using
this QAQQINI setting, take care with its usage.
• In general, expressions in the index must match the expression in the query.

SELECT * FROM EMPLOYEE


WHERE SALARY+COMM+BONUS > 50000

In this example, the SALARY+COMM+BONUS expression is in a different order than the index key
SALARY+BONUS+COMM and would not match.
• It is recommended that derived index keys be kept as simple as possible. The index is less likely to be
selected when a complex query expression and a complex index key expression need to be matched.
• The CQE optimizer has limited support for matching derived key indexes.
Related reference
Derived key index
You can use the SQL CREATE INDEX statement to create a derived key index using an SQL expression.
Related information
SQL Create Index statement

290 IBM i: Performance and Query Optimization


Using sparse indexes
SQL indexes can be created using WHERE selection predicates. These indexes can also be referred to as
sparse indexes. The advantage of a sparse index is that fewer entries are maintained in the index. Only
those entries matching the WHERE selection criteria are maintained in the index.
In general, the query WHERE selection must be a subset of the sparse index WHERE selection in order for
the sparse index to be used.
Here is a simple example of when a sparse index can be used:

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

It is recommended that the WHERE selection in the sparse index is kept as simple as possible. The more
complex the WHERE selection, the more difficult it becomes to match the sparse index WHERE selection
to the query WHERE selection. Then it is less likely that the sparse index is used. The CQE optimizer does
not support sparse indexes. It does support select/omit logical files however. The SQE optimizer matches
the CQE optimizer in its support for select/omit logical files and has nearly full support for sparse indexes.
Related reference
Sparse indexes
You can use the SQL CREATE INDEX statement to create a sparse index using SQL selection predicates.
Related information
SQL Create Index statement

Using indexes with sort sequence


The following sections provide useful information about how indexes work with sort sequence tables.

Using indexes and sort sequence with selection, joins, or grouping


Before using an existing index, Db2 for i ensures the attributes of the columns (selection, join, or grouping
columns) match the attributes of the key columns in the existing index. The sort sequence table is an
additional attribute that must be compared.
The query sort sequence table (specified by the SRTSEQ and LANGID) must match the index sort
sequence table. Db2 for i compares the sort sequence tables. If they do not match, the existing index
cannot be used.
There is an exception to this rule, however. If the sort sequence table associated with the query is
a unique-weight sequence table (including *HEX), Db2 for i acts as though no sort sequence table is
specified for selection, join, or grouping columns that use the following operators and predicates:
• equal (=) operator
• not equal (^= or <>) operator
• LIKE predicate (OPNQRYF %WLDCRD and *CT)
• IN predicate (OPNQRYF %VALUES)
When these conditions are true, Db2 for i is free to use any existing index where the key columns match
the columns and either:
• The index does not contain a sort sequence table or
• The index contains a unique-weight sort sequence table
Note:
1. The table does not need to match the unique-weight sort sequence table associated with the query.

Database performance and query optimization 291


2. Bitmap processing has a special consideration when multiple indexes are used for a table. If two or
more indexes have a common key column referenced in the query selection, then those indexes must
either use the same sort sequence table or no sort sequence table.

Using indexes and sort sequence with ordering


Unless the optimizer chooses a sort to satisfy the ordering request, the index sort sequence table must
match the query sort sequence table.
When a sort is used, the translation is done during the sort. Since the sort is handling the sort sequence
requirement, this technique allows Db2 for i to use any existing index that meets the selection criteria.

Index examples
The following index examples are provided to help you create effective indexes.
For the purposes of the examples, assume that three indexes are created.
Assume that an index HEXIX was created with *HEX as the sort sequence.

CREATE INDEX HEXIX ON STAFF (JOB)

Assume that an index UNQIX was created with a unique-weight sort sequence.

CREATE INDEX UNQIX ON STAFF (JOB)

Assume that an index SHRIX was created with a shared-weight sort sequence.

CREATE INDEX SHRIX ON STAFF (JOB)

Index example: Equal selection with no sort sequence table


Equal selection with no sort sequence table (SRTSEQ(*HEX)).

SELECT * FROM STAFF


WHERE JOB = 'MGR'

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF))
QRYSLT('JOB *EQ ''MGR''')
SRTSEQ(*HEX)

The system can use either index HEXIX or index UNQIX.

Index example: Equal selection with a unique-weight sort sequence table


Equal selection with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).

SELECT * FROM STAFF


WHERE JOB = 'MGR'

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF))
QRYSLT('JOB *EQ ''MGR''')
SRTSEQ(*LANGIDUNQ) LANGID(ENU)

The system can use either index HEXIX or index UNQIX.

292 IBM i: Performance and Query Optimization


Index example: Equal selection with a shared-weight sort sequence table
Equal selection with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU)).

SELECT * FROM STAFF


WHERE JOB = 'MGR'

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF))
QRYSLT('JOB *EQ ''MGR''')
SRTSEQ(*LANGIDSHR) LANGID(ENU)

The system can only use index SHRIX.

Index example: Greater than selection with a unique-weight sort sequence


table
Greater than selection with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).

SELECT * FROM STAFF


WHERE JOB > 'MGR'

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF))
QRYSLT('JOB *GT ''MGR''')
SRTSEQ(*LANGIDUNQ) LANGID(ENU)

The system can only use index UNQIX.

Index example: Join selection with a unique-weight sort sequence table


Join selection with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).

SELECT * FROM STAFF S1, STAFF S2


WHERE S1.JOB = S2.JOB

or the same query using the JOIN syntax.

SELECT *
FROM STAFF S1 INNER JOIN STAFF S2
ON S1.JOB = S2.JOB

When using the OPNQRYF command, specify:

OPNQRYF FILE(STAFF STAFF)


FORMAT(FORMAT1)
JFLD((1/JOB 2/JOB *EQ))
SRTSEQ(*LANGIDUNQ) LANGID(ENU)

The system can use either index HEXIX or index UNQIX for either query.

Index example: Join selection with a shared-weight sort sequence table


Join selection with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU)).

SELECT * FROM STAFF S1, STAFF S2


WHERE S1.JOB = S2.JOB

or the same query using the JOIN syntax.

SELECT *
FROM STAFF S1 INNER JOIN STAFF S2
ON S1.JOB = S2.JOB

Database performance and query optimization 293


When using the OPNQRYF command, specify:

OPNQRYF FILE(STAFF STAFF) FORMAT(FORMAT1)


JFLD((1/JOB 2/JOB *EQ))
SRTSEQ(*LANGIDSHR) LANGID(ENU)

The system can only use index SHRIX for either query.

Index example: Ordering with no sort sequence table


Ordering with no sort sequence table (SRTSEQ(*HEX)).

SELECT * FROM STAFF


WHERE JOB = 'MGR'
ORDER BY JOB

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF))
QRYSLT('JOB *EQ ''MGR''')
KEYFLD(JOB)
SRTSEQ(*HEX)

The system can only use index HEXIX.

Index example: Ordering with a unique-weight sort sequence table


Ordering with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).

SELECT * FROM STAFF


WHERE JOB = 'MGR'
ORDER BY JOB

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF))
QRYSLT('JOB *EQ ''MGR''')
KEYFLD(JOB) SRTSEQ(*LANGIDUNQ) LANGID(ENU)

The system can only use index UNQIX.

Index example: Ordering with a shared-weight sort sequence table


Ordering with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU)).

SELECT * FROM STAFF


WHERE JOB = 'MGR'
ORDER BY JOB

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF))
QRYSLT('JOB *EQ ''MGR''')
KEYFLD(JOB) SRTSEQ(*LANGIDSHR) LANGID(ENU)

The system can only use index SHRIX.

294 IBM i: Performance and Query Optimization


Index example: Ordering with ALWCPYDTA(*OPTIMIZE) and a unique-weight
sort sequence table
Ordering with ALWCPYDTA(*OPTIMIZE) and a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ)
LANGID(ENU)).

SELECT * FROM STAFF


WHERE JOB = 'MGR'
ORDER BY JOB

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF))
QRYSLT('JOB *EQ ''MGR''')
KEYFLD(JOB)
SRTSEQ(*LANGIDUNQ) LANGID(ENU)
ALWCPYDTA(*OPTIMIZE)

The system can use either index HEXIX or index UNQIX for selection. Ordering is done during the sort
using the *LANGIDUNQ sort sequence table.

Index example: Grouping with no sort sequence table


Grouping with no sort sequence table (SRTSEQ(*HEX)).

SELECT JOB FROM STAFF


GROUP BY JOB

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF)) FORMAT(FORMAT2)


GRPFLD((JOB))
SRTSEQ(*HEX)

The system can use either index HEXIX or index UNQIX.

Index example: Grouping with a unique-weight sort sequence table


Grouping with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).

SELECT JOB FROM STAFF


GROUP BY JOB

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF)) FORMAT(FORMAT2)


GRPFLD((JOB))
SRTSEQ(*LANGIDUNQ) LANGID(ENU)

The system can use either index HEXIX or index UNQIX.

Index example: Grouping with a shared-weight sort sequence table


Grouping with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU)).

SELECT JOB FROM STAFF


GROUP BY JOB

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF)) FORMAT(FORMAT2)


GRPFLD((JOB))
SRTSEQ(*LANGIDSHR) LANGID(ENU)

The system can only use index SHRIX.

Database performance and query optimization 295


The following examples assume that three more indexes are created over columns JOB and SALARY. The
CREATE INDEX statements precede the examples.
Assume an index HEXIX2 was created with *HEX as the sort sequence.

CREATE INDEX HEXIX2 ON STAFF (JOB, SALARY)

Assume that an index UNQIX2 was created and the sort sequence is a unique-weight sort sequence.

CREATE INDEX UNQIX2 ON STAFF (JOB, SALARY)

Assume an index SHRIX2 was created with a shared-weight sort sequence.

CREATE INDEX SHRIX2 ON STAFF (JOB, SALARY)

Index example: Ordering and grouping on the same columns with a unique-
weight sort sequence table
Ordering and grouping on the same columns with a unique-weight sort sequence table
(SRTSEQ(*LANGIDUNQ) LANGID(ENU)).

SELECT JOB, SALARY FROM STAFF


GROUP BY JOB, SALARY
ORDER BY JOB, SALARY

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF)) FORMAT(FORMAT3)


GRPFLD(JOB SALARY)
KEYFLD(JOB SALARY)
SRTSEQ(*LANGIDUNQ) LANGID(ENU)

The system can use UNQIX2 to satisfy both the grouping and ordering requirements. If index UNQIX2 did
not exist, the system creates an index using a sort sequence table of *LANGIDUNQ.

Index example: Ordering and grouping on the same columns with


ALWCPYDTA(*OPTIMIZE) and a unique-weight sort sequence table
Ordering and grouping on the same columns with ALWCPYDTA(*OPTIMIZE) and a unique-weight sort
sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).

SELECT JOB, SALARY FROM STAFF


GROUP BY JOB, SALARY
ORDER BY JOB, SALARY

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF)) FORMAT(FORMAT3)


GRPFLD(JOB SALARY)
KEYFLD(JOB SALARY)
SRTSEQ(*LANGIDUNQ) LANGID(ENU)
ALWCPYDTA(*OPTIMIZE)

The system can use UNQIX2 to satisfy both the grouping and ordering requirements. If index UNQIX2 did
not exist, the system does one of the following actions:
• Create an index using a sort sequence table of *LANGIDUNQ or
• Use index HEXIX2 to satisfy the grouping and to perform a sort to satisfy the ordering

296 IBM i: Performance and Query Optimization


Index example: Ordering and grouping on the same columns with a shared-
weight sort sequence table
Ordering and grouping on the same columns with a shared-weight sort sequence table
(SRTSEQ(*LANGIDSHR) LANGID(ENU)).

SELECT JOB, SALARY FROM STAFF


GROUP BY JOB, SALARY
ORDER BY JOB, SALARY

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF)) FORMAT(FORMAT3)


GRPFLD(JOB SALARY)
KEYFLD(JOB SALARY)
SRTSEQ(*LANGIDSHR) LANGID(ENU)

The system can use SHRIX2 to satisfy both the grouping and ordering requirements. If index SHRIX2 did
not exist, the system creates an index using a sort sequence table of *LANGIDSHR.

Index example: Ordering and grouping on the same columns with


ALWCPYDTA(*OPTIMIZE) and a shared-weight sort sequence table
Ordering and grouping on the same columns with ALWCPYDTA(*OPTIMIZE) and a shared-weight sort
sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU).

SELECT JOB, SALARY FROM STAFF


GROUP BY JOB, SALARY
ORDER BY JOB, SALARY

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF)) FORMAT(FORMAT3)


GRPFLD(JOB SALARY)
KEYFLD(JOB SALARY)
SRTSEQ(*LANGIDSHR) LANGID(ENU)
ALWCPYDTA(*OPTIMIZE)

The system can use SHRIX2 to satisfy both the grouping and ordering requirements. If index SHRIX2 did
not exist, the system creates an index using a sort sequence table of *LANGIDSHR.

Index example: Ordering and grouping on different columns with a unique-


weight sort sequence table
Ordering and grouping on different columns with a unique-weight sort sequence table
(SRTSEQ(*LANGIDUNQ) LANGID(ENU)).

SELECT JOB, SALARY FROM STAFF


GROUP BY JOB, SALARY
ORDER BY SALARY, JOB

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF)) FORMAT(FORMAT3)


GRPFLD(JOB SALARY)
KEYFLD(SALARY JOB)
SRTSEQ(*LANGIDSHR) LANGID(ENU)

The system can use index HEXIX2 or index UNQIX2 to satisfy the grouping requirements. A temporary
result is created containing the grouping results. A temporary index is then built over the temporary result
using a *LANGIDUNQ sort sequence table to satisfy the ordering requirements.

Database performance and query optimization 297


Index example: Ordering and grouping on different columns with
ALWCPYDTA(*OPTIMIZE) and a unique-weight sort sequence table
Ordering and grouping on different columns with ALWCPYDTA(*OPTIMIZE) and a unique-weight sort
sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).

SELECT JOB, SALARY FROM STAFF


GROUP BY JOB, SALARY
ORDER BY SALARY, JOB

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF)) FORMAT(FORMAT3)


GRPFLD(JOB SALARY)
KEYFLD(SALARY JOB)
SRTSEQ(*LANGIDUNQ) LANGID(ENU)
ALWCPYDTA(*OPTIMIZE)

The system can use index HEXIX2 or index UNQIX2 to satisfy the grouping requirements. A sort is
performed to satisfy the ordering requirements.

Index example: Ordering and grouping on different columns with


ALWCPYDTA(*OPTIMIZE) and a shared-weight sort sequence table
Ordering and grouping on different columns with ALWCPYDTA(*OPTIMIZE) and a shared-weight sort
sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU)).

SELECT JOB, SALARY FROM STAFF


GROUP BY JOB, SALARY
ORDER BY SALARY, JOB

When using the OPNQRYF command, specify:

OPNQRYF FILE((STAFF)) FORMAT(FORMAT3)


GRPFLD(JOB SALARY)
KEYFLD(SALARY JOB)
SRTSEQ(*LANGIDSHR) LANGID(ENU)
ALWCPYDTA(*OPTIMIZE)

The system can use index SHRIX2 to satisfy the grouping requirements. A sort is performed to satisfy the
ordering requirements.

Sparse index examples


This topic shows examples of how the sparse index matching algorithm works.
In example S1, the query selection is a subset of the sparse index selection and consequently an index
scan over the sparse index is used. The remaining query selection (COL3=30) is executed following the
index scan.
Example S1

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

In example S2, the query selection is not a subset of the sparse index selection and the sparse index
cannot be used.
Example S2

298 IBM i: Performance and Query Optimization


CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)
WHERE COL1=10 and COL2=20 and COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20

In example S3, the query selection exactly matches the sparse index selection and an index scan over the
sparse index can be used.
Example S3

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20 and COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

In example S4, the query selection is a subset of the sparse index selection and an index scan over the
sparse index can be used. The remaining query selection (COL3=30) is executed following the index scan.
Example S4

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

In example S5, the query selection is not a subset of the sparse index selection and the sparse index
cannot be used.
Example S5

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20 and COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20

In example S6, the query selection exactly matches the sparse index selection and an index scan over the
sparse index can be used. The query selection is executed following the index scan to eliminate excess
records from the sparse index.
Example S6

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 or COL2=20 or COL3=30

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 or COL2=20 or COL3=30

In example S7, the query selection is a subset of the sparse index selection and an index scan over the
sparse index can be used. The query selection is executed following the index scan to eliminate excess
records from the sparse index.
Example S7

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 or COL2=20 or COL3=30

Database performance and query optimization 299


SELECT COL1, COL2, COL3, COL4
FROM MYLIB/T1
WHERE COL1=10 or COL2=20

In example S8, the query selection is not a subset of the sparse index selection and the sparse index
cannot be used.
Example S8

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 or COL2=20

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 or COL2=20 or COL3=30

In the next example S9, the constant 'MN' was replaced by a parameter marker for the query selection.
The sparse index had the local selection of COL1='MN' applied to it when it was created. The sparse index
matching algorithm matches the parameter marker to the constant 'MN' in the query predicate COL1 =?. It
verifies that the value of the parameter marker is the same as the constant in the sparse index; therefore
the sparse index can be used.
Example S9

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1='MN' or COL2='TWINS'

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
Where Col3='WIN' and (Col1=? or Col2='TWINS')

In the next example S10, the keys of the sparse index match the order by fields in the query. For the
sparse index to satisfy the specified ordering, the optimizer must verify that the query selection is a
subset of the sparse index selection. In this example, the sparse index can be used.
Example S10

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL1, COL3)


WHERE COL1='MN' or COL2='TWINS'

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
Where Col3='WIN' and (Col1='MN' or Col2='TWINS')
ORDER BY COL1, COL3

In the next example S11, the keys of the sparse index do not match the order by fields in the query. But
the selection in sparse index T2 is a superset of the query selection. Depending on size, the optimizer
might choose an index scan over sparse index T2 and then use a sort to satisfy the specified ordering.
Example S11

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL2, COL4)


WHERE COL1='MN' or COL2='TWINS'

SELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
Where Col3='WIN' and (Col1='MN' or Col2='TWINS')
ORDER BY COL1, COL3

The next example S12 represents the classic optimizer decision: is it better to do an index probe using
index IX1 or is it better to do an index scan using sparse index SPR1? Both indexes retrieve the same
number of index entries and have the same cost from that point forward. For example, both indexes have
the same cost to retrieve the selected records from the dataspace, based on the retrieved entries/keys.
The cost to retrieve the index entries is the deciding criteria. In general, if index IX1 is large then an index
scan over sparse index SPR1 has a lower cost to retrieve the index entries. If index IX1 is rather small

300 IBM i: Performance and Query Optimization


then an index probe over index IX1 has a lower cost to retrieve the index entries. Another cost decision
is reusability. The plan using sparse index SPR1 is not as reusable as the plan using index IX1 because of
the static selection built into the sparse selection.
Example S12

CREATE INDEX MYLIB/IX1 on MYLIB/T1 (COL1, COL2, COL3)

CREATE INDEX MYLIB/SPR1 on MYLIB/T1 (COL3)


WHERE COL1=10 and COL2=20 and COL3=30

CSELECT COL1, COL2, COL3, COL4


FROM MYLIB/T1
WHERE COL1=10 and COL2=20 and COL3=30

Application design tips for database performance


There are some design tips that you can apply when designing SQL applications to maximize your
database performance.

Using live data


The term live data refers to the type of access that the database manager uses when it retrieves data
without making a copy of the data. Using this type of access, the data, which is returned to the program,
always reflects the current values of the data in the database. The programmer can control whether
the database manager uses a copy of the data or retrieves the data directly. This control is done by
specifying the allow copy data (ALWCPYDTA) parameter on the precompiler commands or the Start SQL
(STRSQL) command.
Specifying ALWCPYDTA(*NO) instructs the database manager to always use live data. In most cases,
forcing live data access is a detriment to performance. It severely limits the possible plan choices that
the optimizer could use to implement the query. Avoid it in most cases. However, in specialized cases
involving a simple query, live data access can be used as a performance advantage. The cursor does not
need to be closed and opened again to refresh the data being retrieved.
An example application demonstrating this advantage is one that produces a list on a display. If the
display can show only 20 list elements at a time, then, after the initial 20 elements are displayed, the
programmer can request that the next 20 rows be displayed. A typical SQL application designed for an
operating system other than the IBM i operating system, might be structured as follows:

EXEC SQL
DECLARE C1 CURSOR FOR
SELECT EMPNO, LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
ORDER BY EMPNO
END-EXEC.

EXEC SQL
OPEN C1
END-EXEC.

* PERFORM FETCH-C1-PARA 20 TIMES.

MOVE EMPNO to LAST-EMPNO.

EXEC SQL
CLOSE C1
END-EXEC.

* Show the display and wait for the user to indicate that
* the next 20 rows should be displayed.

EXEC SQL
DECLARE C2 CURSOR FOR
SELECT EMPNO, LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
WHERE EMPNO > :LAST-EMPNO
ORDER BY EMPNO

Database performance and query optimization 301


END-EXEC.

EXEC SQL
OPEN C2
END-EXEC.

* PERFORM FETCH-C21-PARA 20 TIMES.

* Show the display with these 20 rows of data.

EXEC SQL
CLOSE C2
END-EXEC.

In the preceding example, notice that an additional cursor had to be opened to continue the list and to get
current data. This technique can result in creating an additional ODP that increases the processing time
on the system. In place of the preceding example, the programmer can design the application specifying
ALWCPYDTA(*NO) with the following SQL statements:

EXEC SQL
DECLARE C1 CURSOR FOR
SELECT EMPNO, LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
ORDER BY EMPNO
END-EXEC.

EXEC SQL
OPEN C1
END-EXEC.

* Display the screen with these 20 rows of data.

* PERFORM FETCH-C1-PARA 20 TIMES.

* Show the display and wait for the user to indicate that
* the next 20 rows should be displayed.

* PERFORM FETCH-C1-PARA 20 TIMES.

EXEC SQL
CLOSE C1
END-EXEC.

In the preceding example, the query might perform better if the FOR 20 ROWS clause was used on the
multiple-row FETCH statement. Then, the 20 rows are retrieved in one operation.
Related information
Start SQL Interactive Session (STRSQL) command

Reducing the number of open operations


The SQL data manipulation language statements must do database open operations in order to create an
open data path (ODP) to the data. An open data path is the path through which all input/output operations
for the table are performed. In a sense, it connects the SQL application to a table. The number of open
operations in a program can significantly affect performance.
A database open operation occurs on:
• An OPEN statement
• SELECT INTO statement
• An INSERT statement with a VALUES clause
• An UPDATE statement with a WHERE condition
• An UPDATE statement with a WHERE CURRENT OF cursor and SET clauses that refer to operators or
functions
• SET statement that contains an expression
• VALUES INTO statement that contains an expression
• A DELETE statement with a WHERE condition

302 IBM i: Performance and Query Optimization


An INSERT statement with a select-statement requires two open operations. Certain forms of subqueries
could also require one open per subselect.
To minimize the number of opens, Db2 for i leaves the open data path (ODP) open and reuses the ODP if
the statement is run again, unless:
• The ODP used a host variable to build a subset temporary index. The optimizer could choose to build
a temporary index with entries for only the rows that match the row selection specified in the SQL
statement. If a host variable was used in the row selection, the temporary index does not have the
entries required for a different host variable value.
• Ordering was specified on a host variable value.
• An Override Database File (OVRDBF) or Delete Override (DLTOVR) CL command has been
issued since the ODP was opened, which affects the SQL statement execution.
Note: Only overrides that affect the name of the table being referred to causes the ODP to be closed
within a given program invocation.
• The join is a complex join that requires temporary objects to contain the intermediate steps of the join.
• Some cases involve a complex sort, where a temporary file is required, might not be reusable.
• A change to the library list since the last open has occurred, which changes the table selected by an
unqualified referral in system naming mode.
• The join was implemented by the CQE optimizer using hash join.
For embedded static SQL, Db2 for i only reuses ODPs opened by the same statement. An identical
statement coded later in the program does not reuse an ODP from any other statement. If the identical
statement must be run in the program many times, code it once in a subroutine and call the subroutine to
run the statement.
The ODPs opened by Db2 for i are closed when any of the following occurs:
• a CLOSE, INSERT, UPDATE, DELETE, or SELECT INTO statement completes and the ODP required a
temporary result that was not reusable or a subset temporary index.
• the Reclaim Resources (RCLRSC) command is issued. A Reclaim Resources (RCLRSC) is
issued when the first COBOL program on the call stack ends or when a COBOL program issues the
STOP RUN COBOL statement. Reclaim Resources (RCLRSC) does not close the ODPs created
for programs precompiled using CLOSQLCSR(*ENDJOB). For interaction of Reclaim Resources
(RCLRSC) with non-default activation groups, see the following books:
– WebSphere® Development Studio: ILE C/C++ Programmer's Guide
– WebSphere Development Studio: ILE COBOL Programmer's Guide
– WebSphere Development Studio: ILE RPG Programmer's Guide
• the last program containing SQL statements on the call stack exits. Exception is for ODPs
created for programs precompiled using CLOSQLCSR(*ENDJOB) or modules precompiled using
CLOSQLCSR(*ENDACTGRP).
• a CONNECT (Type 1) statement changes the application server for an activation group, all ODPs created
for the activation group are closed.
• a DISCONNECT statement ends a connection to the application server, all ODPs for that application
server are closed.
• a released connection is ended by a successful COMMIT, all ODPs for that application server are closed.
• the threshold for open cursors specified by the query options file (QAQQINI) parameter
OPEN_CURSOR_THRESHOLD is reached.
• the SQL LOCK TABLE or CL ALCOBJ OBJ((filename *FILE *EXCL)) CONFLICT(*RQSRLS) command closes
any pseudo-closed cursors associated with the specified table.
• an application has requested a close, but the data path was left open. The ODP can be forced closed
for a specific file by using the ALCOBJ CL command. This close does not force the ODP to close if
the application has not requested that the cursor be closed. The syntax for the command is: ALCOBJ
OBJ((library/file *FILE *EXCL)) CONFLICT(*RQSRLS).

Database performance and query optimization 303


• an MQT plan expired based on the timestamp.
• an incompatible commitment control change occurred.
• the table size changed beyond tolerance. The optimizer needs to reoptimize based on the new table
size.
• a new index or indexes were created. The optimizer can cost a plan created with the new indexes and
compare its cost to the previous plan.
• new statistics were created. The optimizer can take advantage of these new statistics to create a more
efficient plan.
• host variables are incompatible with a non-reusable MTI, an MQT, or a sparse index used to implement
the query.
• data is warm (in memory).
• the OPTIMIZATION_GOAL *All IO or *First IO specified in query options file QAQQINI was changed.
• a hard close was forced.
The optimizer does not recognize that query selectivity has changed due to host variable changes. It
continues to use the existing open and access plan. Change of selectivity due to host variables is only
evaluated at full open time unless the PSEUDO_OPEN_CHECK_HOST_VARS qaqqini option is altered.
You can control whether the system keeps the ODPs open in the following ways:
• Design the application so a program that issues an SQL statement is always on the call stack
• Use the CLOSQLCSR(*ENDJOB) or CLOSQLCSR(*ENDACTGRP) parameter
• By specifying the OPEN_CURSOR_THRESHOLD and OPEN_CURSOR_CLOSE_COUNT parameters of the
query options file (QAQQINI)
You can control whether the optimizer factors in host variable selectivity once in pseudo mode for queries
with host variable that have considerable selectivity variability.
• By specifying the PSEUDO_OPEN_CHECK_HOST_VARS parameter of the query options file (QAQQINI)
An open operation occurs for the first execution of each UPDATE WHERE CURRENT OF, when any SET
clause expression contains an operator or function. The open can be avoided by coding the function or
operation in the host language code.
For example, the following UPDATE causes the system to do an open operation:

EXEC SQL
FETCH EMPT INTO :SALARY
END-EXEC.

EXEC SQL
UPDATE CORPDATA.EMPLOYEE
SET SALARY = :SALARY + 1000
WHERE CURRENT OF EMPT
END-EXEC.

Instead, use the following coding technique to avoid opens:

EXEC SQL
FETCH EMPT INTO :SALARY
END EXEC.

ADD 1000 TO SALARY.

EXEC SQL
UPDATE CORPDATA.EMPLOYEE
SET SALARY = :SALARY
WHERE CURRENT OF EMPT
END-EXEC.

You can determine whether SQL statements result in full opens in several ways. The preferred methods
are to use the Database Monitor or by looking at the messages issued while debug is active. You can also
use the CL commands Trace Job (TRCJOB) or Display Journal (DSPJRN).

304 IBM i: Performance and Query Optimization


Related information
Reclaim Resources (RCLRSC) command
Trace Job (TRCJOB) command
Display Journal (DSPJRN) command
RPG
COBOL
C and C++

Retaining cursor positions


You can improve performance by retaining cursor positions.

Retaining cursor positions for non-ILE program calls


For non-ILE program calls, the close SQL cursor (CLOSQLCSR) parameter allows you to specify the scope
of the following:
• The cursors
• The prepared statements
• The locks
When used properly, the CLOSQLCSR parameter can reduce the number of SQL OPEN, PREPARE, and
LOCK statements needed. It can also simplify applications by allowing you to retain cursor positions
across program calls.

*ENDPGM The default for all non-ILE precompilers. With this option, a cursor remains open and
accessible only while the program that opened it is on the call stack. When the program
ends, the SQL cursor can no longer be used. Prepared statements are also lost when the
program ends. Locks, however, remain until the last SQL program on the call stack has
completed.
*ENDSQL SQL cursors and prepared statements that are created by a program remain open until the
last SQL program on the call stack has completed. They cannot be used by other programs,
only by a different call to the same program. Locks remain until the last SQL program in the
call stack completes.
*ENDJOB This option allows you to keep SQL cursors, prepared statements, and locks active for
the duration of the job. When the last SQL program on the stack has completed, any SQL
resources created by *ENDJOB programs are still active. The locks remain in effect. The SQL
cursors that were not explicitly closed by the CLOSE, COMMIT, or ROLLBACK statements
remain open. The prepared statements are still usable on subsequent calls to the same
program.
Related reference
Effects of precompile options on database performance
Several precompile options are available for creating SQL programs with improved performance. They
are only options because using them could impact the function of the application. For this reason, the
default value for these parameters is the value that ensures successful migration of applications from
prior releases. However, you can improve performance by specifying other options.

Retaining cursor positions across ILE program calls


For ILE program calls, the close SQL cursor (CLOSQLCSR) parameter allows you to specify the scope of
the following:
• The cursors
• The prepared statements
• The locks

Database performance and query optimization 305


When used properly, the CLOSQLCSR parameter can reduce the number of SQL OPEN, PREPARE, and
LOCK statements needed. It can also simplify applications by allowing you to retain cursor positions
across program calls.

*ENDACTGRP The default for the ILE precompilers. With this option, SQL cursors and prepared
statements remain open until the activation group that the program is running under
ends. They cannot be used by other programs, only by a different call to the same
program. Locks remain until the activation group ends.
*ENDMOD With this option, a cursor remains open and accessible only while the module that
opened it is active. When the module ends, the SQL cursor can no longer be used.
Prepared statements are also lost when the module ends. Locks, however, remain until
the last SQL program in the call stack completes.

General rules for retaining cursor positions for all program calls
Programs compiled with either CLOSQLCSR(*ENDPGM) or CLOSQLCSR(*ENDMOD) must open a cursor
every time the program or module is called, in order to access the data. If the SQL program or module is
called several times, and you want to take advantage of a reusable ODP, then the cursor must be explicitly
closed before the program or module exits.
Using the CLOSQLCSR parameter and specifying *ENDSQL, *ENDJOB, or *ENDACTGRP, you might not
need to run an OPEN and a CLOSE statement on every call. In addition to having fewer statements to run,
you can maintain the cursor position between calls to the program or module.
The following examples of SQL statements help demonstrate the advantage of using the CLOSQLCSR
parameter:

EXEC SQL
DECLARE DEPTDATA CURSOR FOR
SELECT EMPNO, LASTNAME
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = :DEPTNUM
END-EXEC.

EXEC SQL
OPEN DEPTDATA
END-EXEC.

EXEC SQL
FETCH DEPTDATA INTO :EMPNUM, :LNAME
END-EXEC.

EXEC SQL
CLOSE DEPTDATA
END-EXEC.

If this program is called several times from another SQL program, it is able to use a reusable ODP.
This technique means that, as long as SQL remains active between the calls to this program, the OPEN
statement does not require a database open operation. However, the cursor is still positioned to the first
result row after each OPEN statement, and the FETCH statement will always return the first row.
In the following example, the CLOSE statement has been removed:

EXEC SQL
DECLARE DEPTDATA CURSOR FOR
SELECT EMPNO, LASTNAME
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = :DEPTNUM
END-EXEC.

IF CURSOR-CLOSED IS = TRUE THEN


EXEC SQL
OPEN DEPTDATA
END-EXEC.

EXEC SQL
FETCH DEPTDATA INTO :EMPNUM, :LNAME
END-EXEC.

306 IBM i: Performance and Query Optimization


If this program is precompiled with the *ENDJOB or *ENDACTGRP option and the activation group
remains active, the cursor position is maintained. The cursor position is also maintained when the
following occurs:
• The program is precompiled with the *ENDSQL option.
• SQL remains active between program calls.
The result of this strategy is that each call to the program retrieves the next row in the cursor. On
subsequent data requests, the OPEN statement is unnecessary and, in fact, fails with a -502 SQLCODE.
You can ignore the error, or add code to skip the OPEN. Use a FETCH statement first, and then run the
OPEN statement only if the FETCH operation failed.
This technique also applies to prepared statements. A program can first try the EXECUTE, and if it fails,
perform the PREPARE. The result is that the PREPARE is only needed on the first call to the program,
assuming that the correct CLOSQLCSR option was chosen. If the statement can change between calls to
the program, perform the PREPARE in all cases.
The main program might also control cursors by sending a special parameter on the first call only. This
special parameter value indicates that because it is the first call, the subprogram performs the OPENs,
PREPAREs, and LOCKs.
Note: If you are using COBOL programs, do not use the STOP RUN statement. When the first COBOL
program on the call stack ends or a STOP RUN statement runs, a reclaim resource (RCLRSC) operation is
done. This operation closes the SQL cursor. The *ENDSQL option does not work as you wanted.

Programming techniques for database performance


By changing the coding of your queries, you can improve their performance.

Use the OPTIMIZE clause


If an application is not going to retrieve the entire result table for a cursor, using the OPTIMIZE clause
can improve performance. The query optimizer modifies the cost estimates to retrieve the subset of rows
using the value specified on the OPTIMIZE clause.
Assume that the following query returns 1000 rows:

EXEC SQL
DECLARE C1 CURSOR FOR
SELECT EMPNO, LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = 'A00'
ORDER BY LASTNAME
OPTIMIZE FOR 100 ROWS
END EXEC.

Note: The values that can be used for the preceding OPTIMIZE clause are 1–9999999 or ALL.
The optimizer calculates the following costs.
The optimize ratio = optimize for n rows value / estimated number of rows in answer set.

Cost using a temporarily created index:

Cost to retrieve answer set rows


+ Cost to create the index
+ Cost to retrieve the rows again
with a temporary index * optimize ratio

Cost using a SORT:

Cost to retrieve answer set rows


+ Cost for SORT input processing
+ Cost for SORT output processing * optimize ratio

Cost using an existing index:

Database performance and query optimization 307


Cost to retrieve answer set rows
using an existing index * optimize ratio

In the previous examples, the estimated cost to sort or to create an index is not adjusted by the optimize
ratio. This method allows the optimizer to balance the optimization and preprocessing requirements.
If the optimize number is larger than the number of rows in the result table, no adjustments are made to
the cost estimates.
If the OPTIMIZE clause is not specified for a query, a default value is used based on the statement type,
value of ALWCPYDTA, or output device.

Table 59. OPTIMIZE FOR n ROWS default value


Statement Type ALWCPYDTA(*OPTIMIZE) ALWCPYDTA(*YES or *NO)
DECLARE CURSOR The number or rows in the result 30 rows or the number of rows in
table. the result table.
Embedded Select 2 2
INTERACTIVE Select output to 30 rows or the number of rows in 30 rows or the number of rows in
display the result table. the result table.
INTERACTIVE Select output to The number of rows in the result The number of rows in the result
printer or database table table. table.

The OPTIMIZE clause influences the optimization of a query:


• To use an existing index (by specifying a small number).
• To enable the creation of an index, or run a sort or hash by specifying many possible rows in the answer
set.
Related information
select-statement

Use FETCH FOR n ROWS


Applications that perform many FETCH statements in succession could be improved by using FETCH FOR
n ROWS. With this clause, you can retrieve multiple rows of table data with a single FETCH, putting them
into a host structure array or row storage area.
An SQL application that uses a FETCH statement without the FOR n ROWS clause can be improved
by using the multiple-row FETCH statement to retrieve multiple rows. After the host structure array or
row storage area is filled by the FETCH, the application loops through the data, processing each of the
individual rows. The statement runs faster because the SQL run-time was called only once and all the data
was simultaneously returned to the application program.
You can change the application program to allow the database manager to block the rows that the SQL
run-time retrieves from the tables.
In the following table, the program attempted to FETCH 100 rows into the application. Note the
differences in the table for the number of calls to SQL runtime and the database manager when blocking
can be performed.

Table 60. Number of Calls Using a FETCH Statement


Database Manager Not Using Database Manager Using
Blocking Blocking
Single-Row FETCH Statement 100 SQL calls 100 database calls 100 SQL calls one database call
Multiple-Row FETCH Statement one SQL runtime call 100 one SQL runtime call one
database calls database call

308 IBM i: Performance and Query Optimization


Related information
FETCH statement

Improve SQL blocking performance when using FETCH FOR n ROWS


Use these performance techniques to improve SQL blocking performance when using FETCH FOR n
ROWS.
You can improve SQL blocking performance with the following:
• Match the attribute information in the host structure array or the descriptor associated with the row
storage area with the attributes of the columns retrieved.
• Retrieve as many rows as possible with a single multiple-row FETCH call. The blocking factor for a
multiple-row FETCH request is not controlled by the system page sizes or the SEQONLY parameter on
the OVRDBF command. It is controlled by the number of rows that are requested on the multiple-row
FETCH request.
• Do not mix single- and multiple-row FETCH requests against the same cursor within a program. If one
FETCH against a cursor is treated as a multiple-row FETCH, all fetches against that cursor are treated as
multiple-row fetches. In that case, each of the single-row FETCH requests is treated as a multiple-row
FETCH of one row.
• Do not use the PRIOR, CURRENT, and RELATIVE scroll options with multiple-row FETCH statements.
To allow random movement of the cursor by the application, the database manager must maintain the
same cursor position as the application. Therefore, the SQL run-time treats all FETCH requests against a
scrollable cursor with these options specified as multiple-row FETCH requests.

Use INSERT n ROWS


Applications that perform many INSERT statements in succession could be improved by using INSERT
n ROWS. With this clause, you can insert one or more rows of data from a host structure array into a
target table. This array must be an array of structures where the elements of the structure correspond to
columns in the target table.
An SQL application that loops over an INSERT...VALUES statement (without the n ROWS clause) can
be improved by using the INSERT n ROWS statement to insert multiple rows into the table. After the
application has looped to fill the host array with rows, a single INSERT n ROWS statement inserts the
entire array into the table. The statement runs faster because the SQL runtime was only called once and
all the data was simultaneously inserted into the target table.
In the following table, the program attempted to INSERT 100 rows into a table. Note the differences in the
number of calls to SQL runtime and to the database manager when blocking can be performed.

Table 61. Number of Calls Using an INSERT Statement


Database Manager Not Using Database Manager Using
Blocking Blocking
Single-Row INSERT Statement 100 SQL runtime calls 100 100 SQL runtime calls one
database calls database call
Multiple-Row INSERT Statement 1 SQL runtime call 100 database 1 SQL runtime call 1 database
calls call

Related information
INSERT statement

Database performance and query optimization 309


Control database manager blocking
To improve performance, the SQL runtime attempts to retrieve and insert rows from the database
manager a block at a time whenever possible.
You can control blocking, if you want. Use the SEQONLY parameter on the CL command
Override Database File (OVRDBF) before calling the application program that contains the SQL
statements. You can also specify the ALWBLK parameter on the CRTSQLxxx commands or use the
QSY2.OVERRIDE_TABLE application service.
The database manager does not allow blocking in the following situations:
• The cursor is update or delete capable.
• The length of the row plus the feedback information is greater than 32767. The minimum size for the
feedback information is 11 bytes. The feedback size is increased by the number of bytes in the index
key columns used by the cursor, and the number of key columns, if any, that are null capable.
• COMMIT(*CS) is specified, and ALWBLK(*ALLREAD) is not specified.
• COMMIT(*ALL) is specified, and the following are true:
– A SELECT INTO statement or a blocked FETCH statement is not used
– The query does not use column functions or specify group by columns.
– A temporary result table does not need to be created.
• COMMIT(*CHG) is specified, and ALWBLK(*ALLREAD) is not specified.
• The cursor contains at least one subquery and the outermost subselect provided a correlated reference
for a subquery, or the outermost subselect processed a subquery with an IN, = ANY, or < > ALL
subquery predicate operator, which is treated as a correlated reference, and that subquery is not
isolatable.
The SQL runtime automatically blocks rows with the database manager in the following cases:
• INSERT
If an INSERT statement contains a select-statement, inserted rows are blocked and not inserted into
the target table until the block is full. The SQL runtime automatically does blocking for blocked inserts.
Note: If an INSERT with VALUES is specified, the SQL runtime might not close the internal cursor used
to perform the inserts until the program ends. If the same INSERT statement is run again, a full open is
not necessary and the application runs much faster.
• OPEN
Blocking is done under the OPEN statement when the rows are retrieved if all the following conditions
are true:
– The cursor is only used for FETCH statements.
– No EXECUTE or EXECUTE IMMEDIATE statements are in the program, or ALWBLK(*ALLREAD) was
specified, or the cursor is declared with the FOR FETCH ONLY clause.
– COMMIT(*CHG) and ALWBLK(*ALLREAD) are specified, COMMIT(*CS) and ALWBLK(*ALLREAD) are
specified, or COMMIT(*NONE) is specified.
Related reference
OVERRIDE_TABLE procedure
The OVERRIDE_TABLE procedure sets the blocking size for a table. This procedure uses the Override with
Database File (OVRDBF) and Delete Override (DLTOVR) CL commands to control the blocking factor when
the file is accessed within the current job.
Effects of precompile options on database performance
Several precompile options are available for creating SQL programs with improved performance. They
are only options because using them could impact the function of the application. For this reason, the
default value for these parameters is the value that ensures successful migration of applications from
prior releases. However, you can improve performance by specifying other options.

310 IBM i: Performance and Query Optimization


Related information
Override Database File (OVRDBF) command

Optimize the number of columns that are selected with SELECT statements
For each column in the SELECT statement, the database manager retrieves the data from the underlying
table and maps it to a host variable in the application program. By minimizing the number of columns that
are specified, processing unit resource usage can be conserved.
Even though it is convenient to code SELECT *, it is far better to explicitly code the columns that are
required for the application. This technique is especially important for index-only access, or if all the
columns participate in a sort operation (as in SELECT DISTINCT and SELECT UNION).
This technique is also important when considering index only access. You minimize the number of
columns in a query and increase the odds that an index can be used to completely satisfy the data
request.
Related information
select-statement

Eliminate redundant validation with SQL PREPARE statements


The processing which occurs when an SQL PREPARE statement is run is like the processing which occurs
during precompile processing.
The following processing occurs for the statement that is being prepared:
• The syntax is checked.
• The statement is validated to ensure that the usage of objects is valid.
• An access plan is built.
Again when the statement is executed or opened, the database manager revalidates that the access plan
is still valid. Much of this open processing validation is redundant with the validation which occurred
during the PREPARE processing. The DLYPRP(*YES) parameter specifies whether PREPARE statements in
this program completely validates the dynamic statement. The validation is completed when the dynamic
statement is opened or executed. This parameter can provide a significant performance enhancement for
programs which use the PREPARE SQL statement because it eliminates redundant validation. Programs
that specify this precompile option must check the SQLCODE and SQLSTATE after running the OPEN
or EXECUTE statement to ensure that the statement is valid. DLYPRP(*YES) does not provide any
performance improvement if the INTO clause is used on the PREPARE statement, or if a DESCRIBE
statement uses the dynamic statement before an OPEN is issued for the statement.
Related reference
Effects of precompile options on database performance
Several precompile options are available for creating SQL programs with improved performance. They
are only options because using them could impact the function of the application. For this reason, the
default value for these parameters is the value that ensures successful migration of applications from
prior releases. However, you can improve performance by specifying other options.
Related information
Prepare statement

Page interactively displayed data with REFRESH(*FORWARD)


In large tables, paging performance is typically degraded because of the REFRESH(*ALWAYS) parameter
on the Start SQL (STRSQL) command. STRSQL dynamically retrieves the latest data directly from the
table. Paging performance can be improved by specifying REFRESH(*FORWARD).
When interactively displaying data using REFRESH(*FORWARD), the results of a select-statement are
copied to a temporary table as you page forward through the display. Other users sharing the table can
change the rows while you are displaying the select-statement results. If you page backward or forward

Database performance and query optimization 311


to rows that have already been displayed, the rows shown are in the temporary table instead of the
updated table.
The refresh option can be changed on the Session Services display.
Related information
Start SQL (STRSQL) command

Improve concurrency by avoiding lock waits


The concurrent access resolution option directs the database manager on how to handle cases of record
lock conflicts under certain isolation levels.
The concurrent access resolution, when applicable, can have one of the following values:
• Wait for outcome (default). This value directs the database manager to wait for the commit or rollback
when encountering locked data in the process of being updated or deleted. Locked rows that are in
the process of being inserted are not skipped. This option does not apply for read-only queries running
under isolation level None or Uncommitted Read.
• Use currently committed. This value allows the database manager to use the currently committed
version of the data for read-only queries when encountering locked data in the process of being updated
or deleted. Locked rows in the process of being inserted can be skipped. This option applies if possible
when the isolation level in effect is Cursor Stability and is ignored otherwise.
• Skip locked data. This value directs the database manager to skip rows in the case of record lock
conflicts. This option is applicable only when the query is running under an isolation level of Cursor
Stability or Read Stability and additionally for UPDATE and DELETE queries when the isolation level is
None or Uncommitted Read.
The concurrent access resolution values of USE CURRENTLY COMMITTED and SKIP LOCKED DATA can
be used to improve concurrency by avoiding lock waits. However, care must be used when using these
options because they might affect application functionality. For more information on the USE CURRENTLY
COMMITTED option, see Concurrency.
WAIT FOR OUTCOME, USE CURRENTLY COMMITTED, and SKIP LOCKED DATA can be specified as the
concurrent-access-resolution-clause in the attribute-string of a PREPARE statement.
Additionally, they can be specified as the concurrent-access-resolution-clause at the statement level on a
select-statement, SELECT INTO, searched UPDATE, or searched DELETE statement.
Concurrent access resolution is also specifiable as a precompiler option by using the CONACC parameter
on the CRTSQLxxx. The CONACC parameter accepts one of the following values:
• *DFT - specifies that the concurrent access option is not explicitly set for this program. The
value that is in effect when the program is invoked is used. The value can be set using the
SQL_CONCURRENT_ACCESS_RESOLUTION option in the query options file QAQQINI.
• *CURCMT - use currently committed.
• *WAIT - wait for outcome.
These same options can be set on the RUNSQLSTM and RUNSQL CL commands and by using the SET
OPTION SQL statement. Concurrent access resolution can be specified for SQL triggers, functions, and
procedures by using the SET OPTION statement.
When the concurrent access resolution option is not directly set by the application, it is set to the value
of the SQL_CONCURRENT_ACCESS_RESOLUTION option in the query options file QAQQINI. This option
accepts one of the following values:
• *DEFAULT - the default value is set to *WAIT.
• *CURCMT - use currently committed.
• *WAIT - wait for outcome.
Related reference
QAQQINI query options

312 IBM i: Performance and Query Optimization


There are different options available for parameters in the QAQQINI file.
Related information
concurrent-access-resolution-clause
Concurrency

Use SELECTIVITY to supply missing information


Some query predicates are inherently difficult for the optimizer to analyze, yet effective optimization
depends on accurate information about the data being selected. When other statistics are unavailable,
careful use of the SELECTIVITY clause can give the optimizer the information it needs to produce the best
access plan for a query.
The optimizer uses a variety of techniques to evaluate and estimate the number of rows a query
predicate will select. This information may come from key range estimates, from column statistics, or
from inferences based on the cardinality of the data. Sometimes, however, the optimizer has no way to
determine how a predicate will apply to the underlying data. In these cases, the SELECTIVITY clause can
be added to difficult predicates to provide the extra information that the optimizer needs.

Using SELECTIVITY to correct inaccurate estimates


One common type of incomplete information involves data that is transformed before it is used in a
predicate. The transformation could be performed by a user defined function or it could be performed
by a built in function. In either case, something about the function prevents the optimizer from making
inferences about how the transformation will affect the data.
Consider the following query:

SELECT EXCHANGE, S.SYMBOL, NAME, CURRENT_POSITION


FROM SECURITIES S INNER JOIN POSITIONS P ON S.SYMBOL = P.SYMBOL
WHERE RISK_SCORE(EXCHANGE, S.SYMBOL) > .8
AND EXCHANGE = 'NYSE'
AND CURRENT_POSITION > 1000
ORDER BY EXCHANGE, S.SYMBOL

Because the optimizer does not know the internal logic of the RISK_SCORE function, it uses a
default selectivity value. The optimizer will generally assume 33% of the rows satisfy the predicate
RISK_SCORE(EXCHANGE, S.SYMBOL) > .8. If this assumption is not accurate, it could cause the optimizer
to select an inappropriate query plan. To mitigate this, a user who understands the behavior of the
RISK_SCORE function and knows that only 1% of the rows in the table will satisfy the predicate can
rewrite the WHERE clause as:

WHERE RISK_SCORE(EXCHANGE, S.SYMBOL) > .8 SELECTIVITY .01


AND EXCHANGE = 'NYSE'
AND CURRENT_POSITION > 10000

Another common cause of missing information is when the query selects a small number of rows that
have been added to the table very recently. These rows may not yet be reflected in the statistical
information automatically maintained by the statistics manager, leading the optimizer to believe that
the query selects no rows. As in the above example, the solution is to add a SELECTIVITY clause that
accurately represents the percentage of rows selected by the predicate.
To determine when the use of SELECTIVITY could be helpful for a query, use Visual Explain to identify
operations with significantly inaccurate Percent Selectivity attributes under the Estimated rows selected
and query join info heading. In many cases, you may have a reasonable intuition for the correct selectivity
for the operation. In cases where you need additional information, either Run and Explain or use Visual
Explain on a plan that is cached in the plan cache, since these options provide you with information about
the actual number of rows processed by each operation. These values are given as Actual Rows Selected
Per Plan Step Iteration and can be compared to the estimated Rows Selected Per Plan Step Iteration.
Keep in mind that a given operation could process multiple predicates that have been logically combined.
Since SELECTIVITY applies to an individual predicate, the effect of SELECTIVITY on the overall Percent
Selectivity of the operation can be difficult to predict. In general, the effect of adding SELECTIVITY is

Database performance and query optimization 313


easiest to predict and understand when the operation has only a single simple predicate (for example, a
UDF.)

Using SELECTIVITY to reduce plan volatility


The optimizer uses a variety of factors when re-validating whether a cached access plan should be
re-used. One key factor is the selectivity of the query's predicates. The same predicate with different host
variable values may select a very different number of rows and thus run best with a different access plan.
For this reason, the optimizer will not re-use a cached plan that it estimates will select a significantly
different number of rows. Instead, it will re-optimize the query with the new values.
Under some circumstances, you may prefer to use a single plan for all host variable values rather than
relying on the dynamic behavior of the optimizer. If the plan is changing due to the selectivity of a host
variable value changing, the SELECTIVITY clause can help to lock in a preferred plan.
For example, consider the following query where the plan changes depending on the given value (for
example, 1000 rows vs 1,000,000 rows are returned.)

SELECT ... FROM EMPLOYEE WHERE SALARY > ?

If the preferred plan is known to occur when SALARY > 40000 and it is known that 20% of the rows are
selected by this predicate, then this query can be rewritten as:

SELECT ... FROM EMPLOYEE WHERE SALARY > ? SELECTIVITY .2

When running this query, changes to the host variable value will no longer influence the optimized plan.

Considerations for using SELECTIVITY


While SELECTIVITY can be useful when applied carefully, it can also produce some surprising results.
Used without care, SELECTIVITY can cause more harm than benefit.
The optimizer integrates multiple pieces of information - including I/O costs, predicate selectivity, and
correlation between columns - to form a coherent model of the data and the environment. By overriding
the internal model, a user-provided SELECTIVITY value may introduce inconsistencies into and reduce
some of the benefits of the model. As a result, SELECTIVITY can lead to less accurate estimates of I/O
costs. It may also prevent the optimizer from detecting correlation between related columns and thereby
reduce the accuracy of the estimates for the overall set of predicates.
Furthermore, by locking in a single value, SELECTIVITY prevents the optimizer from automatically
responding to changes in the underlying data. As the data grows and changes, the SELECTIVITY value
may become inaccurate, requiring you to occasionally re-evaluate and adjust it.
For these reasons, SELECTIVITY is best reserved for use in the limited situations described in this section.
Before using SELECTIVITY to solve a query performance problem, follow the other recommendations in
this document. For example, creating a new index or column statistic might help the optimizer not simply
with one but with many queries. Keep in mind that a hard-to-optimize query may be a sign that re-writing
the query or improving the data model is a better long-term strategy. SELECTIVITY should be a last resort
when no other options exist for providing the optimizer with the needed information.

314 IBM i: Performance and Query Optimization


General Db2 for i performance considerations
As you code your applications, there are some general tips that can help you optimize performance.

Effects on database performance when using long object names


Long object names are converted internally to system object names when used in SQL statements. This
conversion can have some performance impacts. Names of tables, views, indexes, and aliases that are 30
characters or less will generally perform much better than names longer than 30 characters.
Qualify the long object name with a library name and the conversion to the short name happens at
precompile time. In this case, there is minimal performance impact when the statement is executed.
Otherwise, the conversion is done at execution time and has a small performance impact.

Effects of precompile options on database performance


Several precompile options are available for creating SQL programs with improved performance. They
are only options because using them could impact the function of the application. For this reason, the
default value for these parameters is the value that ensures successful migration of applications from
prior releases. However, you can improve performance by specifying other options.
The following table shows these precompile options and their performance impacts.
Some of these options might be suitable for most of your applications. Use the command CRTDUPOBJ to
create a copy of the SQL CRTSQLxxx command. and the CHGCMDDFT command to customize the optimal
values for the precompile parameters. The DSPPGM, DSPSRVPGM, DSPMOD, or PRTSQLINF commands can
be used to show the precompile options that are used for an existing program object.

Table 62. Precompile options and their performance impacts


Precompile Option Optimal Value Improvements Considerations
ALWCPYDTA *OPTIMIZE (the default) Queries where the A copy of the data could
ordering or grouping be made when the query
criteria conflicts with the is opened.
selection criteria.
ALWBLK *ALLREAD (the default) Additional read-only ROLLBACK HOLD might
cursors use blocking. not change the position
of a read-only cursor.
Dynamic processing of
positioned updates or
deletes might fail.
CLOSQLCSR *ENDJOB, *ENDSQL, or Cursor position can be Implicit closing of SQL
*ENDACTGRP retained across program cursor is not done when
invocations. the program invocation
ends.
DLYPRP *YES Programs using SQL Complete validation of
PREPARE statements the prepared statement
could run faster. is delayed until the
statement is run or
opened.
TGTRLS *CURRENT (the default) The precompiler can The program object
generate code that takes cannot be used on a
advantage of performance system from a previous
enhancements available release.
in the current release.

Database performance and query optimization 315


Related reference
Effects of the ALWCPYDTA parameter on database performance
Some complex queries can perform better by using a sort or hashing method to evaluate the query
instead of using or creating an index.
Control database manager blocking
To improve performance, the SQL runtime attempts to retrieve and insert rows from the database
manager a block at a time whenever possible.
Retaining cursor positions for non-ILE program calls
For non-ILE program calls, the close SQL cursor (CLOSQLCSR) parameter allows you to specify the scope
of the following:
Eliminate redundant validation with SQL PREPARE statements
The processing which occurs when an SQL PREPARE statement is run is like the processing which occurs
during precompile processing.

Effects of the ALWCPYDTA parameter on database performance


Some complex queries can perform better by using a sort or hashing method to evaluate the query
instead of using or creating an index.
By using the sort or hash, the database manager is able to separate the row selection from the ordering
and grouping process. Bitmap processing can also be partially controlled through this parameter. This
separation allows the use of the most efficient index for the selection. For example, consider the following
SQL statement:

EXEC SQL
DECLARE C1 CURSOR FOR
SELECT EMPNO, LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = 'A00'
ORDER BY LASTNAME
END-EXEC.

The above SQL statement can be written in the following way by using the OPNQRYF command:

OPNQRYF FILE(CORPDATA/EMPLOYEE)
FORMAT(FORMAT1)
QRYSLT(WORKDEPT *EQ ''AOO'')
KEYFLD(LASTNAME)

In the preceding example, when ALWCPYDTA(*NO) or ALWCPYDTA(*YES) is specified, the database


manager could try to create an index from the first index with a column named LASTNAME, if such an
index exists. The rows in the table are scanned, using the index, to select only the rows matching the
WHERE condition.
If ALWCPYDTA(*OPTIMIZE) is specified, the database manager uses an index with the first index column
of WORKDEPT. It then makes a copy of all the rows that match the WHERE condition. Finally, it could sort
the copied rows by the values in LASTNAME. This row selection processing is more efficient, because the
index used immediately locates the rows to be selected.
ALWCPYDTA(*OPTIMIZE) optimizes the total time that is required to process the query. However, the time
required to receive the first row could be increased because a copy of the data must be made before
returning the first row of the result table. This initial change in response time could be important for
applications that are presenting interactive displays or that retrieve only the first few rows of the query.
The Db2 for i query optimizer can be influenced to avoid sorting in memory by using the OPTIMIZE clause.
Queries that involve a join operation might also benefit from ALWCPYDTA(*OPTIMIZE) because the join
order can be optimized regardless of the ORDER BY specification.
Related concepts
Plan cache

316 IBM i: Performance and Query Optimization


The plan cache is a repository that contains the access plans for queries that were optimized by SQE.
Related reference
Effects of precompile options on database performance
Several precompile options are available for creating SQL programs with improved performance. They
are only options because using them could impact the function of the application. For this reason, the
default value for these parameters is the value that ensures successful migration of applications from
prior releases. However, you can improve performance by specifying other options.
Radix index scan
A radix index scan operation is used to retrieve the rows from a table in a keyed sequence. Like a table
scan, all the rows in the index are sequentially processed, but the resulting row numbers are sequenced
based upon the key columns.
Radix index probe
A radix index probe operation is used to retrieve the rows from a table in a keyed sequence. The main
difference between the radix index probe and the scan is that the rows returned are first identified by a
probe operation to subset them.

Tips for using VARCHAR and VARGRAPHIC data types in databases


Variable-length column (VARCHAR or VARGRAPHIC) support allows you to define any number of columns
in a table as variable length. If you use VARCHAR or VARGRAPHIC support, the size of a table can typically
be reduced.
Data in a variable-length column is stored internally in two areas: a fixed-length or ALLOCATE area and
an overflow area. If a default value is specified, the allocated length is at least as large as the value. The
following points help you determine the best way to use your storage area.
When you define a table with variable-length data, you must decide the width of the ALLOCATE area. If
the primary goal is:
• Space saving: use ALLOCATE(0).
• Performance: the ALLOCATE area must be wide enough to incorporate at least 90% to 95% of the
values for the column.
It is possible to balance space savings and performance. In the following example of an electronic
telephone book, the following data is used:
• 8600 names that are identified by: last, first, and middle name
• The Last, First, and Middle columns are variable length.
• The shortest last name is two characters; the longest is 22 characters.
This example shows how space can be saved by using variable-length columns. The fixed-length column
table uses the most space. The table with the carefully calculated allocate sizes uses less disk space. The
table that was defined with no allocate size (with all the data stored in the overflow area) uses the least
disk space.

Table 63. Disk space used with variable-length columns


Number of
Rows in
Variety of Last Name First Name Middle Name Total Physical Overflow
Support Max/Alloc Max/Alloc Max/Alloc File Size Space
Fixed Length 22 22 22 567 K 0
Variable Length 40/10 40/10 40/7 408 K 73
Variable-Length 40/0 40/0 40/0 373 K 8600
Default

Database performance and query optimization 317


In many applications, performance must be considered. If you use the default ALLOCATE(0), it doubles
the disk unit traffic. ALLOCATE(0) requires two reads; one to read the fixed-length portion of the row and
one to read the overflow space. The variable-length implementation, with the carefully chosen ALLOCATE,
minimizes overflow and space and maximizes performance. The size of the table is 28% smaller than
the fixed-length implementation. Because 1% of rows are in the overflow area, the access requiring two
reads is minimized. The variable-length implementation performs about the same as the fixed-length
implementation.
Varying length columns with a length less than 30 may be implemented by the database using a non-zero
allocate value. As a result, changing the allocated length for these columns may not impact the disk I/O
performance efficiency.
To create the table using the ALLOCATE keyword:

CREATE TABLE PHONEDIR


(LAST VARCHAR(40) ALLOCATE(10),
FIRST VARCHAR(40) ALLOCATE(10),
MIDDLE VARCHAR(40) ALLOCATE(7))

If you are using host variables to insert or update variable-length columns, use variable length host
variables. Because blanks are not truncated from fixed-length host variables, using fixed-length host
variables can cause more rows to spill into the overflow space. This increases the size of the table.
In this example, fixed-length host variables are used to insert a row into a table:

01 LAST-NAME PIC X(40).



MOVE "SMITH" TO LAST-NAME.
EXEC SQL
INSERT INTO PHONEDIR
VALUES(:LAST-NAME, :FIRST-NAME, :MIDDLE-NAME, :PHONE)
END-EXEC.

The host-variable LAST-NAME is not variable length. The string “SMITH”, followed by 35 blanks, is
inserted into the VARCHAR column LAST. The value is longer than the allocate size of 10. 30 of 35 trailing
blanks are in the overflow area.
In this example, variable-length host variables are used to insert a row into a table:

01 VLAST-NAME.
49 LAST-NAME-LEN PIC S9(4) BINARY.
49 LAST-NAME-DATA PIC X(40).

MOVE "SMITH" TO LAST-NAME-DATA.
MOVE 5 TO LAST-NAME-LEN.
EXEC SQL
INSERT INTO PHONEDIR
VALUES(:VLAST-NAME, :VFIRST-NAME, :VMIDDLE-NAME, :PHONE)
END-EXEC.

The host variable VLAST-NAME is variable length. The actual length of the data is set to 5. The value is
shorter than the allocated length. It can be placed in the fixed portion of the column.
Running the Reorganize Physical File Member (RGZPFM) command against tables that contain
variable-length columns can improve performance. The fragments in the overflow area that are not in use
are compacted by the Reorganize Physical File Member (RGZPFM) command. This technique
reduces the read time for rows that overflow, increases the locality of reference, and produces optimal
order for serial batch processing.
Choose the appropriate maximum length for variable-length columns. Selecting lengths that are too long
increases the process access group (PAG). A large PAG slows performance. A large maximum length
makes SEQONLY(*YES) less effective. Variable-length columns longer than 2000 bytes are not eligible as
key columns.

318 IBM i: Performance and Query Optimization


Using LOBs and VARCHAR in the same table
Storage for LOB columns allocated in the same manner as VARCHAR columns. When a column stored in
the overflow storage area is referenced, currently all the columns in that area are paged into memory. A
reference to a "smaller" VARCHAR column that is in the overflow area can potentially force extra paging of
LOB columns. For example, A VARCHAR(256) column retrieved by application has side-effect of paging in
two 5 MB BLOB columns that are in the same row. In order to prevent this side-effect, you might want to
use ALLOCATE keyword to ensure that only LOB columns are stored in the overflow area.
Related information
Reorganize Physical File Member (RGZPFM) command
Reorganizing a physical file
Embedded SQL programming

Using field procedures to provide column level encryption


Field procedures can provide column level encryption in Db2 for i.
A field procedure is a user-written exit routine to transform values in a single column. When values in
the column are changed, or new values inserted, the field procedure is invoked for each value. The field
procedure can transform that value (encode it) in any way. The encoded value is then stored. When
values are retrieved from the column, the field procedure is invoked for each encoded value. The field
procedure decodes each value back to the original value. Any indexes defined on a column that uses a
field procedure are built with encoded values.
Field procedures are assigned to a table by the FIELDPROC clause of CREATE TABLE and ALTER TABLE.
A field procedure that is specified for a column is invoked in three general situations:
• For field-definition, when the CREATE TABLE or ALTER TABLE statement that names the procedure is
executed. During this invocation, the procedure is expected to:
– Determine whether the data type and attributes of the column are valid.
– Verify the literal list, and change it if wanted.
– Provide the field description of the column.
• For field-encoding, when a column value is field-encoded. That occurs for any value that:
– is inserted in the column by an SQL INSERT statement, SQL MERGE statement, or native write.
– is changed by an SQL UPDATE statement, SQL MERGE statement, or native update.
– is the target column for a copy from a column with an associated field procedure. The field procedure
might be invoked to encode the copied data. Examples include SQL Statements ALTER TABLE or
CREATE TABLE LIKE/AS and CL commands CPYF and RGZPFM.
– is compared to a column with a field procedure. The QAQQINI option
FIELDPROC_ENCODED_COMPARISON is used to determine if the column value is decoded, or the
host variable, constant, or join column is encoded.
– is the DEFAULT value for a column with an associated field procedure in a CREATE or ALTER TABLE
statement.
If there are any after or read triggers, the field procedure is invoked before any of these triggers. If there
are any before triggers, the field procedure is invoked after the before trigger.
• For field-decoding, when a stored value is field-decoded back into its original value. Field-decoding
occurs for any value that:
– is retrieved by an SQL SELECT or FETCH statement, or by a native read.
– is a column with an associated field procedure that is copied. The field procedure might be invoked
to decode the data before making the copy. Examples include SQL Statements ALTER TABLE, CREATE
TABLE LIKE/AS, and CL commands CPYF and RGZPFM.

Database performance and query optimization 319


– 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 host 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.

Improving performance
For queries that use field procedures, the path length is longer due to the additional processing of calling
the field procedure. In order to improve performance of queries, the SQE optimizer:
• attempts to remove decoding operations, based on the QAQQINI FIELDPROC_ENCODED COMPARISON
setting.
• matches existing indexes over columns that have an associated field procedure.
• creates and uses MTIs over columns with field procedures. The MTI will be created as non-resuable
which means it will not be shared between queries.
• creates statistics over the encoded values through statistics collection.
The SQE optimizer attempts to do the following optimizations:
• optimization of predicates that compare a field procedure column to a constant or host variable. For
example, predicate FP1(4, C1) = ‘abc' is optimized as C1 = FP1(0,‘abc'). With this specific example, the
optimization is done as long as the QAQQINI option is not *NONE.
• remove field procedure decoding operations from join predicates when the same field procedure is
applied to both sides of the join predicate, and no compatibility conversion is required. For example,
join predicate FP1(4,T1.C1) > FP1(4,T2.C1) is rewritten as T1.C1 > T2.C1. With this specific example, the
optimization is done as long as the QAQQINI option is either *ALLOW_RANGE or *ALL. This technique is
also applied to = predicates when the QAQQINI option is *ALLOW_EQUAL.
• remove field procedures from GROUP BY and ORDER BY clauses. For example, ORDER BY FP1(4,C1) is
rewritten as ORDER BY C1 if the QAQQINI setting is either *ALLOW_RANGE or *ALL
The CQE optimizer does not look at the QAQQINI option, which means it always runs in *NONE mode.
*NONE mode requires that all references to the column are decoded before any other operation is
performed. A CQE query does not match any existing indexes when the column has an associated field
procedure. If an index is required, a temporary index is built with the index keys decoded.
Related reference
QAQQINI query options
There are different options available for parameters in the QAQQINI file.
Related information
Defining field procedures
CREATE TABLE

Field procedure examples


The following examples show various field procedure-related optimizations done by the SQE optimizer.
The examples show the FieldProc name along with the encoding (field procedure function code 0) or
decoding (field procedure function code 4) in the pseudo-SQL. These codes indicate how the optimizer is
optimizing the field procedure calls.
Given the following table and index:

CREATE TABLE T1 (col1 CHAR(10), col2 CHAR(10) FIELDPROC ‘FP1')


CREATE INDEX IX1 on T1(col2)

320 IBM i: Performance and Query Optimization


Example 1
A user query written as:

SELECT col1, col2 FROM T1 WHERE col2 = ‘abc'

Is represented by the optimizer as:

SELECT col1, FP1(4, col2) FROM T1 WHERE FP1(4,col2) = ‘abc'

Note the FP1 with the decode operation around the COL2 references in the SELECT list and the WHERE
clause.
Assuming the QAQQINI FIELDPROC_ENCODED COMPARISON is set to *ALLOW_EQUAL, *ALLOW_RANGE
or *ALL:
The query optimizer rewrites the query as:

SELECT col1, ‘abc' FROM T1 WHERE col2 = FP1(0, ‘abc')

This rewrite allows the query optimizer to use the encoded index IX1 to implement the WHERE clause and
only cause one invocation of the field procedure for the query.

Example 2

SELECT col2 FROM T1 ORDER BY col2

Is represented by the query optimizer as:

SELECT FP1(4, col2) FROM T1 ORDER BY FP1(4, col2)

The optimized version removes the FieldProc from the ORDER BY clause assuming that the field
procedure QAQQINI option is set to *ALLOW_RANGE or *ALL:

SELECT FP1(4, col2) FROM T1 ORDER BY col2

Example 3

Select col2, COUNT(*) FROM T1 GROUP BY col2

Is represented by the query optimizer as:

Select FP1(4, col2), COUNT(*) FROM T1 GROUP BY FP1(4, col2)

The optimized version removes the field procedure invocation from the GROUP BY clause column col2,
allowing it to group the encoded data and only run the field procedure once per group. The decoded
grouped data is returned to the user. This optimization is done if the field procedure QAQQINI option is
set to *ALLOW_RANGE or *ALL:

SELECT FP1(4, col2), COUNT(*) FROM T1 GROUP BY col2

IS NULL/IS NOT NULL predicate does not require calling the field procedure field-decode option 4. The
field procedure cannot change the nullability of the field.

Db2 for i Services


There are many system-provided views, procedures, and functions.
These are grouped in the following categories.

Database performance and query optimization 321


Application Services
These procedures provide interfaces that are useful for application development.

DELIMIT_NAME scalar function


The DELIMIT_NAME function returns a name with delimiters if the delimiters are needed for use in an SQL
statement.
Authorization: None required.

DELIMIT_NAME ( name )

The schema is QSYS2.

name A character or graphic string expression that identifies a name. The string must contain only
characters allowed in an SQL identifier. If the string is longer than 128 characters, it will be
truncated to 128 characters.

The result of the function is a varying length character string that contains name correctly delimited. This
includes delimiting reserved words. If name is the null value or an empty string, null is returned.

Example
• Delimit these names:

VALUES DELIMIT_NAME('ABC'),
DELIMIT_NAME('abc'),
DELIMIT_NAME('test"name'),
DELIMIT_NAME('test''name2'),
DELIMIT_NAME('NEW')

Returns the values:

ABC
"abc"
"test""name"
"test'name2"
"NEW"

OVERRIDE_QAQQINI procedure
The OVERRIDE_QAQQINI procedure creates and modifies a temporary version of the QAQQINI file.
The temporary QAQQINI file will be created in QTEMP. It inherits all query options that are already
in place for the job. The OVERRIDE_QAQQINI procedure can be called multiple times to establish job
specific QAQQINI settings.
The procedure can also be called to discard the temporary customization settings.
Authorization: For most QAQQINI options, none is required. For the following three options, the caller
must have *JOBCTL special authority or be authorized to the QIBM_DB_SQLADM function usage ID. These
options are more restrictive because they can affect the performance of other jobs.
• QUERY_TIME_LIMIT when the option-value is not 0.
• STORAGE_LIMIT
• PARALLEL_DEGREE

322 IBM i: Performance and Query Optimization


OVERRIDE_QAQQINI ( override-option
OVERRIDE_OPTION =>

, option-name
OPTION_NAME =>

)
, option-value
OPTION_VALUE =>

The schema is QSYS2.

override- An integer value that indicates the function to perform.


option
1 Create the QAQQINI override file. A procedure call with this override-option value
must be run before option 2 can be used to change QAQQINI options.
2 Set a QAQQINI option to the specified value. See “QAQQINI query options” on page
196 for the list of options and values.
3 Discard the temporary QAQQINI file.

option-name A character or graphic string expression that identifies the name of the QAQQINI option to
be changed.
This parameter is required when override-option is 2. For options 1 and 3, it can be
omitted or passed as the empty string.
option-value A character or graphic string expression that identifies the value to assign to the QAQQINI
option identified by option-name.
This parameter is required when override-option is 2. For options 1 and 3, it can be
omitted or passed as the empty string.

Example
• Establish the temporary override for QAQQINI. The job's current QAQQINI values will be used as the
initial values.

CALL QSYS2.OVERRIDE_QAQQINI(1);

• Improve the chances that you can acquire an exclusive lock for a database file. Multiple calls to the
procedure can be used to change more than one QAQQINI value.

CALL QSYS2.OVERRIDE_QAQQINI(2, 'PREVENT_ADDITIONAL_CONFLICTING_LOCKS', '*YES');

• Discard the temporary QAQQINI file and revert to using the job's version of the QAQQINI file.

CALL QSYS2.OVERRIDE_QAQQINI(3);

OVERRIDE_TABLE procedure
The OVERRIDE_TABLE procedure sets the blocking size for a table. This procedure uses the Override with
Database File (OVRDBF) and Delete Override (DLTOVR) CL commands to control the blocking factor when
the file is accessed within the current job.
Authorization: The caller must have *USE authority to the OVRDBF and DLTOVR CL commands.

OVERRIDE_TABLE ( schema-name , table-name , blocking-size )

Database performance and query optimization 323


The schema is QSYS2.

schema-name A character string expression containing the name of the schema.


table-name A character string expression containing the name of the table.
blocking-size A character string expression containing the blocking size. It can be a specific byte count
or a special value of *BUF32KB, *BUF64KB, *BUF128KB, or *BUF256KB.

Example
• Override the EMPLOYEE table to use 256K blocking for sequential processing.

CALL QSYS2.OVERRIDE_TABLE('CORPDATA', 'EMP', '*BUF256KB');

• Remove the override.

CALL QSYS2.OVERRIDE_TABLE('CORPDATA', 'EMP', 0);

Related reference
Control database manager blocking
To improve performance, the SQL runtime attempts to retrieve and insert rows from the database
manager a block at a time whenever possible.

PARSE_STATEMENT table function


The PARSE_STATEMENT table function returns a list of object and column names that are used in an SQL
query, data change statement, or other statement where a query or expression is specified.
Authorization: None required.

PARSE_STATEMENT ( SQL-statement
SQL_STATEMENT =>

, naming
NAMING =>

, decimal-point
DECIMAL_POINT =>

)
, SQL-string-delimiter
SQL_STRING_DELIMITER =>

The schema is QSYS2.

SQL-statement A character or graphic string expression that contains a valid SQL statement. The
maximum string length is 2 megabytes.
naming A character or graphic string expression that defines the naming rule for the statement.

*SYS System naming rules apply. This is the default.


*SQL SQL naming rules apply.

decimal-point A character or graphic string expression that defines the decimal point for numeric
constants in SQL-statement.

324 IBM i: Performance and Query Optimization


*PERIOD or . The decimal point is the period. This is the default.
*COMMA or , The decimal point is the comma.

SQL-string- A character or graphic string expression that defines the string delimiter for strings
delimiter in SQL-statement. Delimited identifiers in the SQL statement will use the opposite
character.

*APOSTSQL or ' The apostrophe character (') is used to delimit strings. This is the
default.
*QUOTESQL or " The quote character (") is used to delimit strings.

When the SQL statement is parsed, object names are identified and a result row is returned for every
name. This is done at the SQL parser level where names are identified strictly by where they appear in the
syntax. The following rules apply:
• Names used in data change statements and in any query construct are returned.
• For CALL, the procedure being called is returned.
• For DDL statements, most items are returned. Notable exceptions are:
– RCDFMT name for CREATE TABLE, CREATE VIEW, and CREATE INDEX.
– FIELDPROC program name for CREATE TABLE and ALTER TABLE.
– Columns used as partitioning keys for CREATE TABLE and ALTER TABLE.
– Parameter names for CREATE FUNCTION and CREATE PROCEDURE.
– Return column names for CREATE FUNCTION (Table).
– External program name for functions and procedures.
Any statement that does not contain these constructs, a query, or an expression returns no rows.
• Names in a routine-body, triggered-action, and trigger-body are not returned. To see these references,
use QSYS2.SYSPROGRAMSTMTSTAT to find all the statements for the generated program or service
program and pass each of them as an argument to this table function.
• If the SQL statement is the null value, an empty string, a string of all blanks, or contains a syntax error,
no row is returned.
The result of the function is a table containing a row for each name reference with the format shown in the
following table. All the columns are null capable.

Database performance and query optimization 325


Table 64. PARSE_STATEMENT table function

Column Name Data Type Description

NAME_TYPE VARCHAR(30) Type of object name.

ALIAS This is an alias name.

COLUMN This is a column name, or a global variable name not


returned as a DDL TARGET OBJECT.

CONSTRAINT This is a constraint name.

FUNCTION This is a function name.

INDEX This is an index name.

MASK This is a mask name.

PACKAGE This is a package name.

PARAMETER This is a parameter name for a COMMENT statement.

PERM This is a permission name.

PROC This is a procedure name.

PROGRAM This is the program name for a CREATE FUNCTION,


CREATE PROCEDURE, or CREATE TRIGGER statement.

RETURN COLUMN This is a return column for a COMMENT statement.

ROUTINE This is a routine name for a DDL operation.

SCHEMA This is a schema name.

SEQUENCE This is a sequence name.

SPECIFIC This is a routine specific name for a DDL operation.

TABLE This is a table, view, or alias name.

TRIGGER This is a trigger name.

TYPE This is a user-defined type name.

VARIABLE This is a variable name for a DDL operation.

VIEW This is a view name for a DDL operation.

XSROBJ This is an XSROBJECT name.

NAME VARCHAR(128) The object name.


Contains null if NAME_TYPE is COLUMN without a table qualifier.

SCHEMA VARCHAR(128) The schema name.


Contains null if NAME is not qualified with a schema name.

RDB VARCHAR(128) The relational database name.


Contains null if NAME is not qualified with a relational database name.

COLUMN_NAME VARCHAR(128) The column name.


Contains null if NAME_TYPE is not COLUMN.

ADDITIONAL_NAME VARCHAR(128) Contains an additional name for some name types.


• Name of a member for an alias
• Name of a parameter
• Name of a table function return column
• System object name when FOR SYSTEM NAME provided in DDL
• System column name when two column names provided in DDL
Contains null if there is no additional name.

326 IBM i: Performance and Query Optimization


Table 64. PARSE_STATEMENT table function (continued)

Column Name Data Type Description

USAGE_TYPE VARCHAR(17) How this name is used in the statement.

CHECK Column is used in a check constraint.


CONSTRAINT

DDL SOURCE Name identifies the table an index or trigger is being


OBJECT created on, the table referenced by CREATE TABLE
LIKE, the table referenced by an alias, or the object
being renamed.

DDL TARGET Name is the primary object of a DDL statement or the


OBJECT new name for a renamed object.

EXPRESSION Name is referenced in an index key expression.

FOREIGN KEY Column is used in a foreign key constraint.

HISTORY TABLE Table is the history table for an ALTER TABLE statement
with ADD VERSIONING.

PARAMETER Name is referenced in a parameter default expression.


DEFAULT

PRIMARY KEY Column is used in a primary key constraint.

QUERY Name is referenced as part of a query construct.

REFERENCES Name is part of a foreign key constraint referencing


another table.

TARGET This is the procedure that is the target of a CALL


PROCEDURE statement.

TARGET TABLE This is the table that will be affected for an insert,
update, delete, merge, truncate, lock table, or refresh
table statement. The value is also returned for any
explicitly specified columns from the target table for
insert, update, and merge.

UNIQUE KEY Column is used in a unique key constraint.

NAME_START_POSITION INTEGER Position within the SQL-statement string that this name begins. For qualified
TABLE names, this is the position where the RDB or schema name begins. For all
other name types, this is the position of the name.

Database performance and query optimization 327


Table 64. PARSE_STATEMENT table function (continued)

Column Name Data Type Description

SQL_STATEMENT_TYPE VARCHAR(32) Type of SQL statement.


• ALTER FUNCTION
• ALTER MASK
• ALTER PERMISSION
• ALTER PROCEDURE
• ALTER SEQUENCE
• ALTER TABLE
• ALTER TRIGGER
• ASSOCIATE LOCATOR
• CALL
• COMMENT ALIAS
• COMMENT COLUMN
• COMMENT CONSTRAINT
• COMMENT FUNCTION
• COMMENT INDEX
• COMMENT MASK
• COMMENT PACKAGE
• COMMENT PARAMETER
• COMMENT PERMISSION
• COMMENT PROCEDURE
• COMMENT RETURN COLUMN
• COMMENT ROUTINE
• COMMENT SEQUENCE
• COMMENT TABLE
• COMMENT TRIGGER
• COMMENT TYPE
• COMMENT VARIABLE
• COMMENT XSROBJECT

328 IBM i: Performance and Query Optimization


Table 64. PARSE_STATEMENT table function (continued)

Column Name Data Type Description

SQL_STATEMENT_TYPE (continued) • CREATE ALIAS


• CREATE FUNCTION
• CREATE INDEX
• CREATE MASK
• CREATE PERMISSION
• CREATE PROCEDURE
• CREATE SCHEMA
• CREATE SEQUENCE
• CREATE TABLE
• CREATE TRIGGER
• CREATE TYPE
• CREATE VARIABLE
• CREATE VIEW
• DECLARE CURSOR
• DECLARE GLOBAL TEMPORARY TABLE
• DELETE
• DESCRIBE PROCEDURE
• DROP ALIAS
• DROP FUNCTION
• DROP INDEX
• DROP MASK
• DROP PACKAGE
• DROP PERMISSION
• DROP PROCEDURE
• DROP ROUTINE
• DROP SCHEMA
• DROP SEQUENCE
• DROP TABLE
• DROP TRIGGER
• DROP TYPE
• DROP VARIABLE
• DROP VIEW
• DROP XSROBJECT
• EXECUTE IMMEDIATE
• GRANT FUNCTION
• GRANT PACKAGE
• GRANT PROCEDURE
• GRANT ROUTINE
• GRANT SCHEMA
• GRANT SEQUENCE
• GRANT TABLE
• GRANT TYPE
• GRANT VARIABLE
• GRANT XSROBJECT
• INSERT

Database performance and query optimization 329


Table 64. PARSE_STATEMENT table function (continued)

Column Name Data Type Description

SQL_STATEMENT_TYPE (continued) • LABEL ALIAS


• LABEL COLUMN
• LABEL CONSTRAINT
• LABEL FUNCTION
• LABEL INDEX
• LABEL MASK
• LABEL PACKAGE
• LABEL PERMISSION
• LABEL PROCEDURE
• LABEL ROUTINE
• LABEL SCHEMA
• LABEL SEQUENCE
• LABEL TABLE
• LABEL TRIGGER
• LABEL TYPE
• LABEL VARIABLE
• LABEL XSROBJECT
• LOCK TABLE
• MERGE
• PREPARE
• QUERY
• REFRESH TABLE
• RENAME INDEX
• RENAME TABLE
• REVOKE FUNCTION
• REVOKE PACKAGE
• REVOKE PROCEDURE
• REVOKE ROUTINE
• REVOKE SCHEMA
• REVOKE SEQUENCE
• REVOKE TABLE
• REVOKE TYPE
• REVOKE VARIABLE
• REVOKE XSROBJECT
• SET
• SET CURRENT TEMPORAL SYSTEM_TIME
• TRANSFER OWNERSHIP
• TRUNCATE
• UPDATE
• VALUES INTO

Example
For every program and service program in library APPLIB, find all the references to table names in static
SQL statements.

WITH program_statements(naming_mode, dec_point, string_delim, stmt_text,


system_program_name, program_type)
AS (SELECT a.naming, a.decimal_point, a.sql_string_delimiter, b.statement_text,
a.system_program_name, a.program_type
FROM qsys2.sysprogramstat a INNER JOIN
qsys2.sysprogramstmtstat b ON a.program_schema = b.program_schema AND
a.program_name = b.program_name AND
a.module_name = b.module_name
WHERE a.number_statements > 0 AND
a.program_schema = 'APPLIB' AND b.program_schema = 'APPLIB')
SELECT system_program_name, program_type, c.schema, c.name, stmt_text

330 IBM i: Performance and Query Optimization


FROM program_statements,
TABLE(qsys2.parse_statement(stmt_text, naming_mode, dec_point, string_delim)) c
WHERE c.name_type = 'TABLE'
ORDER BY c.schema, c.name;

SELFCODES global variable


This global variable determines the list of SQLCODEs that are handled by the SQL Error Logging Facility
(SELF).
This global variable has the following characteristics:
• It is updateable.
• The type is VARCHAR(256).
• The schema is SYSIBMADM.
• The scope of this global variable is session.
• The default value is null, which corresponds to OFF.
The global variable can be set to a string containing up to 32 SQLCODEs with one or more blanks between
values.
By default, the READ and WRITE privileges on this global variable are granted to PUBLIC.
To change the value of this global variable within a specific job, the user must have the WRITE privilege.
To replace the default value of the global variable, the user must have the authorizations listed for the
CREATE VARIABLE statement, including the OR REPLACE authority. See CREATE VARIABLE.
To confirm that the string value being used with SELFCODES is syntactically correct, use the
“VALIDATE_SELF scalar function” on page 334.

Example
Configure SELF to capture detail for all jobs started in the future, for any SQL statements that fail with
SQLCODE = -913 or SQLCODE = -204.

CREATE OR REPLACE VARIABLE SYSIBMADM.SELFCODES


VARCHAR(256) DEFAULT '-913, -204';

SQL_ERROR_LOG view
The SQL_ERROR_LOG view returns information captured by the SQL Error Logging Facility (SELF).
Authorization: The caller must have *ALLOBJ special authority or be authorized to the
QIBM_DB_SQLADM function usage identifier.
The following table describes the columns in the view. The system name is SQL_ERROR. The schema is
QSYS2.
Table 65. SQL_ERROR_LOG view

Column Name System Column Name Data Type Description

LOGGED_SQLCODE LOG_CODE INTEGER The SQLCODE for this instance of SELF detail.

LOGGED_SQLSTATE LOG_STATE CHAR(5) The SQLSTATE that corresponds to


LOGGED_SQLCODE.

NUMBER_OCCURRENCES MATCHES BIGINT Number of times this LOGGED_SQLCODE has


occurred for this STATEMENT_TEXT from the program
or service program identified by PROGRAM_LIBRARY,
PROGRAM_NAME, and MODULE_NAME.

STATEMENT_TEXT STMTTEXT DBCLOB(2M) CCSID 1200 The SQL statement that encountered the SQLSTATE
that corresponds to LOGGED_SQLCODE. Can contain
the special value of UNKNOWN if the statement text
is not available.

Database performance and query optimization 331


Table 65. SQL_ERROR_LOG view (continued)

Column Name System Column Name Data Type Description

STATEMENT_OPERATION OP_CODE CHAR(2) The SQL statement operation. For a list of values, see
the QQC21 field in “Database monitor view 1000 -
SQL Information” on page 1161.

STATEMENT_OPERATION_DETA OP_DETAIL VARCHAR(50) Descriptive text that corresponds to


IL STATEMENT_OPERATION.

REASON_CODE SQLCODE_RC INTEGER The reason code returned for LOGGED_SQLCODE.


Nullable Contains the null value if LOGGED_SQLCODE has no
reason code.

PROGRAM_LIBRARY PGM_LIB VARCHAR(10) Library containing PROGRAM_NAME. Can contain the


special value of UNKNOWN if the program library is
not available.

PROGRAM_NAME PGM_NAME VARCHAR(10) Program or service program name that encountered


LOGGED_SQLCODE. Can contain the special value of
UNKNOWN if the program name is not available.

PROGRAM_TYPE PGM_TYPE VARCHAR(7) Object type of PROGRAM_NAME.

*PGM This is a program

*SRVPGM This is a service program

*SQLPKG This is an SQL package

Can contain the special value of UNKNOWN if the


program type is not available.

MODULE_NAME MOD_NAME VARCHAR(10) Module name if PROGRAM_NAME is an ILE program


Nullable or service program.
Contains the null value if PROGRAM_NAME is not an
ILE program or service program.

LOGGED_TIME LOG_TIME TIMESTAMP Timestamp of the most recent occurrence of


LOGGED_SQLCODE.

JOB_NAME JOB_NAME VARCHAR(28) The qualified job name of the most recent occurrence
of LOGGED_SQLCODE.

THREAD_ID THREAD_ID BIGINT The thread identifier of the most recent occurrence
of LOGGED_SQLCODE. A thread ID of 0 indicates that
the thread ID is not available.

ADOPTED_USER_NAME ADOPT_USER VARCHAR(10) Value of the CURRENT_USER special register for the
most recent occurrence of LOGGED_SQLCODE.

USER_NAME USER_NAME VARCHAR(10) Value of the USER special register for the most recent
occurrence of LOGGED_SQLCODE.

SYSTEM_USER_NAME SYS_USER VARCHAR(10) Value of the SYSTEM_USER special register for the
most recent occurrence of LOGGED_SQLCODE.

CLIENT_ACCTNG ACCTNG VARCHAR(255) Value of the CURRENT CLIENT_ACCTNG special


Nullable register for the most recent occurrence of
LOGGED_SQLCODE.

Contains the null value if the special register has no


value.

CLIENT_APPLNAME APPLNAME VARCHAR(255) Value of the CURRENT CLIENT_APPLNAME special


Nullable register for the most recent occurrence of
LOGGED_SQLCODE.

Contains the null value if the special register has no


value.

CLIENT_PROGRAMID PROGRAMID VARCHAR(255) Value of the CURRENT CLIENT_PROGRAMID special


Nullable register for the most recent occurrence of
LOGGED_SQLCODE.

Contains the null value if the special register has no


value.

332 IBM i: Performance and Query Optimization


Table 65. SQL_ERROR_LOG view (continued)

Column Name System Column Name Data Type Description

CLIENT_USERID USERID VARCHAR(255) Value of the CURRENT CLIENT_USERID special


Nullable register for the most recent occurrence of
LOGGED_SQLCODE.

Contains the null value if the special register has no


value.

CLIENT_WRKSTNNAME WRKSTNNAME VARCHAR(255) Value of the CURRENT CLIENT_WRKSTNNAME


Nullable special register for the most recent occurrence of
LOGGED_SQLCODE.

Contains the null value if the special register has no


value.

RDB_NAME RDB_NAME VARCHAR(18) Value of the CURRENT_SERVER special register for


the most recent occurrence of LOGGED_SQLCODE.

INITIAL_LOGGED_TIME INIT_TIME TIMESTAMP Timestamp of the initial occurrence of


LOGGED_SQLCODE.

INITIAL_JOB_NAME INIT_JOB VARCHAR(28) Qualified job name of the initial occurrence of


LOGGED_SQLCODE.

INITIAL_THREAD_ID INIT_THD BIGINT The thread identifier of the initial occurrence of


LOGGED_SQLCODE. A thread ID of 0 indicates that
the thread ID is not available.

INITIAL_ADOPTED_USER_NAM INIT_ADOPT VARCHAR(10) Value of the CURRENT_USER special register for the
E most recent occurrence of LOGGED_SQLCODE.

INITIAL_STACK INIT_STACK CLOB(1M) CCSID 1208 The call stack of the current thread for the initial
occurrence of LOGGED_SQLCODE.

SQLCODE_INFO table function


The SQLCODE_INFO table function returns the SQL message associated with the specified SQLCODE
value.
Every non-zero SQLCODE returned by a Db2 for i operation corresponds to a message in the QSQLMSG
message file. This table function returns the message identifier and message text that is associated with a
specific SQLCODE.
Authorization: See Note below.

SQLCODE_INFO ( sqlcode )
P_SQLCODE =>

The schema is SYSTOOLS.

sqlcode An integer value that represents a positive (warning) or negative (error) SQLCODE.
The result of the function is a table containing one row for a recognized SQLCODE value. If an unsupported
SQLCODE value is provided, no row is returned. The columns of the result table are described in the
following table. The result columns are nullable.
Table 66. SQLCODE_INFO table function

Column Name Data Type Description

MESSAGE_ID CHAR(7) The message identifier that corresponds to the SQLCODE.

MESSAGE_TEXT VARGRAPHIC(132) The text of the message.


CCSID 1200

MESSAGE_SECOND_LEVEL_TEXT VARGRAPHIC(3000) The second-level message text of the message.


CCSID 1200

Database performance and query optimization 333


Note
This function is provided in the SYSTOOLS schema as an example of finding a specific message in a
message file. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can be extracted
and used as a model for building similar helper functions, or to create a customized version within a
user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Return the message information for SQLCODE -204.

SELECT * FROM TABLE(SYSTOOLS.SQLCODE_INFO(-204));

VALIDATE_SELF scalar function


The VALIDATE_SELF scalar function is intended to be used with the SQL Error Logging Facility
(SELF). The function can be used to confirm the syntactic validity of a string to be assigned to the
SYSIBMADM.SELFCODES global variable.
The input to VALIDATE_SELF is a comma or space delimited list of positive or negative integers. Positive
integers are denoted with a single leading plus sign (+), or no preceding sign. Negative integers are
denoted with a single leading negative sign (-).
The function validates the syntax of the string. It reorders the list of values in ascending sequence within
a comma separated list.
A successful completion returns a string value that is syntactically valid to be used with SELF for setting
the SYSIBMADM.VALIDATE_SELF global variable.
While the list of values is intended to be comprised of valid SQLCODE values, the function does not verify
that the integer values correspond to defined SQLCODEs. For a list of SQLCODE values supported by Db2
for i, see SQL messages and codes.
To specify all SQLCODEs that are error conditions (negative values), use the special value of *ERROR.
To specify all SQLCODEs that are warning conditions (positive values), use the special value of *WARN.
To specify all SQLCODEs that are error or warning conditions, use the special value of *ALL.
To turn off SELF processing, specify 0 anywhere in the list of values or the special value of *NONE.
Authorization: None required.

VALIDATE_SELF ( self-sqlcodes )
SELF_SQLCODES =>

The schema is SYSIBMADM.

self-sqlcodes A character or graphic string expression that contains one or more SQLCODE values,
separated by commas or blanks.

The string must conform to the following rules:


• An error SQLCODE must be preceded by a single minus sign ('-').
• A warning SQLCODE can be preceded by an optional plus sign ('+').
• Multiple SQLCODE values in the string can be separated by any number of blanks and can have one
comma between values.
• Up to 32 SQLCODE values can be provided in the string.

334 IBM i: Performance and Query Optimization


• A value of 100 or +100 is not allowed.
• A special value or *ERROR, *WARN, *ALL, or *NONE must be the only value in the string.
• If the string contains the value *NONE or zero (0), the character zero (0) is returned, which can be used
to turn off SELF.
The result of the function is VARCHAR(32700).
The function returns the input string as an ordered list of SQLCODE values, separated by a comma and a
space. The positive SQLCODEs are listed first followed by the negative SQLCODEs.

Examples
• Validate a string of SQLCODE values before assigning it to the SELFCODES global variable.

VALUES SYSIBMADM.VALIDATE_SELF('-913, -104,,+406,802');

Returns: '406, 802, -104, -913'


• Turn on SELF for the current session, capturing any instances of SQL statements which complete with
an SQLCODE = 406, 802, -104, or -913.

SET SYSIBMADM.SELFCODES =
SYSIBMADM.VALIDATE_SELF('-913, -104,,+406,802');

• Configure SELF to capture detail for all jobs started in the future, for any SQL statements that fail with
SQLCODE = -913.

CREATE OR REPLACE VARIABLE SYSIBMADM.SELFCODES


VARCHAR(256) DEFAULT (SYSIBMADM.VALIDATE_SELF('-913'));

WLM_SET_CLIENT_INFO procedure
The WLM_SET_CLIENT_INFO procedure sets values for the SQL client special registers.
Authorization: None required.

Database performance and query optimization 335


WLM_SET_CLIENT_INFO (
client-userid
CLIENT_USERID =>

, client-wrkstnname
CLIENT_WRKSTNNAME =>

, client-applname
CLIENT_APPLNAME =>

, client-acctng
CLIENT_ACCTSTR =>

, client-programid
CLIENT_PROGRAMID =>

)
, verbose
VERBOSE =>

The schema is SYSPROC.

client-userid A character or graphic string expression containing the value to set for the CURRENT
CLIENT_USERID special register for the current connection.
If this parameter is omitted, the value of the CURRENT CLIENT_USERID special
register is not changed.
client- A character or graphic string expression containing the value to set for the CURRENT
wrkstnname CLIENT_WRKSTNNAME special register for the current connection.
If this parameter is omitted, the value of the CURRENT CLIENT_WRKSTNNAME special
register is not changed.
client- A character or graphic string expression containing the value to set for the CURRENT
applname CLIENT_APPLNAME special register for the current connection.
If this parameter is omitted, the value of the CURRENT CLIENT_APPLNAME special
register is not changed.
client-acctng A character or graphic string expression containing the value to set for the CURRENT
CLIENT_ACCTNG special register for the current connection.
If this parameter is omitted, the value of the CURRENT CLIENT_ACCTNG special
register is not changed.
client- A character or graphic string expression containing the value to set for the CURRENT
programid CLIENT_PROGRAMID special register for the current connection.
If this parameter is omitted, the value of the CURRENT CLIENT_PROGRAMID special
register is not changed.
verbose A character or graphic string expression that indicates whether the informational,
severity 10 message SQL799C should be sent to the joblog when this procedure is
called. The message lists the changed client special registers and their new values.

NO SQL799C will not be sent to the joblog when this procedure is called.

336 IBM i: Performance and Query Optimization


YES SQL799C will be sent to the joblog when this procedure is called. This is the
default.

Example
• Change the values of the CURRENT CLIENT_USERID and CURRENT CLIENT_PROGRAMID special
registers for the current connection.

CALL SYSPROC.WLM_SET_CLIENT_INFO(CLIENT_USERID => 'PGM1USER',


CLIENT_PROGRAMID => 'PGM1');

Performance Services
These services include procedures that provide interfaces to work with indexes and a view to see
information about database monitors.
Related reference
QAQQINI file override support
If you find working with the QAQQINI query options file cumbersome, consider using the
QSYS2.OVERRIDE_QAQQINI procedure. Instead of creating, managing, and using a QAQQINI *FILE
object directly, this procedure can be called to work with a temporary version of the INI file. It uses
user-specified options and values. The support relies upon the QTEMP library, so any changes affect only
the job which calls the procedure.

ACT_ON_INDEX_ADVICE procedure
The ACT_ON_INDEX_ADVICE procedure creates new indexes for a table based on indexes that have been
advised for the table.
Authorization: See Note below.

ACT_ON_INDEX_ADVICE ( schema-name , table-name ,

times_advised , mti_used , average_estimate )

The schema is SYSTOOLS.

schema-name A character string containing the system name of the schema containing the table.
table-name A character string containing the system name of the table. If NULL is passed, this
parameter is not used to select the target index advice.
times-advised The number of times an index should have been advised before creating a permanent
index. If NULL is passed, this parameter is not used to select the target index advice.
mti-used The number of times a maintained temporary index (MTI) has been used because a
matching permanent index did not exist. If NULL is passed, this parameter is not used
to select the target index advice.
average- The average estimated number of seconds needed to execute the query that drove the
estimate index advice. If NULL is passed, this parameter is not used to select the target index
advice.

For each potential index meeting the specified criteria, a CREATE INDEX statement will be run to generate
the permanent index. A radix index will be named name_RADIX_INDEX_n. An EVI index will be named
name_EVI_INDEX_n. The name represents the table name and n is a unique number. The row containing
this advised index is removed from the QSYS2.SYSIXADV table.

Database performance and query optimization 337


Note
This procedure is provided in the SYSTOOLS schema as an example of how to process index advice using
an SQL procedure. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can be
extracted and used as a model for building similar procedures, or to create a customized version within a
user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Examples
For schema PRODLIB, find all instances of index advice where a maintained temporary index was used
more than 1000 times and create permanent SQL indexes.

CALL SYSTOOLS.ACT_ON_INDEX_ADVICE(‘PRODLIB’,NULL,NULL,1000,NULL)

Related reference
SYSTOOLS
SYSTOOLS is a set of Db2 for IBM i supplied examples and tools.

ACTIVE_QUERY_INFO table function


The ACTIVE_QUERY_INFO table function returns information about active SQL Query Engine (SQE)
queries. An active query is either open or pseudo-closed.
Authorization: None required to see information for the current job.
Otherwise, the caller must have *JOBCTL special authority or be authorized to the QIBM_DB_SQLADM
function usage ID.

ACTIVE_QUERY_INFO (
job-name
JOB_NAME =>

, job-user
JOB_USER =>

, job-number
JOB_NUMBER =>

)
, user-name
USER_NAME =>

The schema is QSYS2.


The values specified on the input parameters are ANDed together.

job-name A character or graphic string expression that contains an unqualified job name that
determines the job information to be returned.
The job name can end with a wildcard character. For example, 'QPADEV*' indicates that any
job name starting with the characters 'QPADEV' is a match.
The string can be the following special values:

338 IBM i: Performance and Query Optimization


* Information for the current job is returned. The job-user and job-number parameters
cannot be specified.
*ALL Information for all job names is returned.

If this parameter is not specified, is an empty string, or is the null value, information for all
jobs is returned.

job-user A character or graphic string expression that contains a user name that determines the job
information to be returned.
The job user name can end with a wildcard character. For example, 'Q*' indicates that any job
user name starting with the character 'Q' is a match.
The string can be the following special value:

*ALL Information for all job user names is returned.

If this parameter is not specified, is an empty string, or is the null value, information for all
users is returned.

job- A character or graphic string expression that contains a job number that determines the job
number information to be returned.
The string can be the following special value:

*ALL Information for all job numbers is returned.

If this parameter is not specified, is an empty string, or is the null value, information for all
job numbers is returned.

user- A character or graphic string expression that contains a user name. This is the user profile
name under which the initial thread is running at this time.
The user name can end with a wildcard character. For example, 'BA*' indicates that any user
name starting with the characters 'BA' is a match.
The string can be the following special value:

*ALL Information for all users is returned.

If this parameter is not specified, is an empty string, or is the null value, the results are not
filtered by the user name used by the initial thread .

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 67. ACTIVE_QUERY_INFO table function

Column Name Data Type Description

QUALIFIED_JOB_NAME VARCHAR(28) The qualified job name.

JOB_NAME VARCHAR(10) The name of the job.

JOB_USER VARCHAR(10) The user profile that started the job.

JOB_NUMBER VARCHAR(6) The job number of the job.

USER_NAME VARCHAR(10) The user profile under which the initial thread is running at this time.
For jobs that swap user profiles, this user profile name and the user
profile that started the job can be different.

Database performance and query optimization 339


Table 67. ACTIVE_QUERY_INFO table function (continued)

Column Name Data Type Description

QUERY_TYPE VARCHAR(6) The type of query.

HLL High Level Language (HLL) open done using SQE. HLL
opens include opens done via RPG, C, and COBOL

NATIVE Native query

SQL SQL query

PSEUDO_CLOSED VARCHAR(3) The current state of the SQL cursor associated with the query.

NO Query is open

YES Query is pseudo-closed

Contains the null value if the query is not an SQL query.

QRO_HASH VARCHAR(8) The QRO_HASH which uniquely identifies an SQE query.

PLAN_IDENTIFIER DECIMAL(20,0) The Plan Identifier of the SQE plan.

FULL_OPEN_TIMESTAMP TIMESTAMP The full open timestamp.

LAST_PSEUDO_OPEN_TIMESTAMP TIMESTAMP The timestamp of the last pseudo-open.


Contains the null value if the query has not been pseudo opened.

LIBRARY_NAME VARCHAR(10) The name of the library that contains FILE_NAME.

FILE_NAME VARCHAR(10) The database file name of the first table referenced by the query.

NUMBER_OF_PSEUDO_CLOSES BIGINT The number of complete runs for this full open of the query.
Returns 0 if this query has not been pseudo-closed.

CURRENT_ROW_COUNT BIGINT If this cursor is not pseudo-closed, the current number of rows
fetched for this run of the query.
Contains the null value if this cursor is currently pseudo-closed.

CURRENT_RUNTIME BIGINT If this cursor is not pseudo-closed, the current runtime in


microseconds for this run of the query.
Contains the null value if this cursor is currently pseudo-closed.

CURRENT_TEMPORARY_STORAGE BIGINT The current amount of temporary storage, in MB, used by the query.
This size does not include storage used by MTIs.

CURRENT_DATABASE_READS BIGINT If this cursor is not pseudo-closed, the current number of


asynchronous and synchronous database reads for this run of the
query.
Contains the null value if this cursor is currently pseudo-closed.

CURRENT_PAGE_FAULTS BIGINT If this cursor is not pseudo-closed, the current number of page faults
for this run of the query.
Contains the null value if this cursor is currently pseudo-closed.

MTI_COUNT BIGINT The number of Maintained Temporary Indexes (MTIs).


Returns 0 if no MTIs are used by the query.

MTI_SIZE BIGINT The current size of MTIs, in MB. This size includes shared MTIs.
Contains the null value if no MTIs are used by the query.

AVERAGE_ROW_COUNT BIGINT The average number of rows fetched for pseudo-closed runs of this
query.
Contains the null value if there are no prior runs.

AVERAGE_RUNTIME BIGINT The average runtime in microseconds for pseudo-closed runs of this
query.
Contains the null value if there are no prior runs.

AVERAGE_TEMPORARY_STORAGE BIGINT The average amount of temporary storage in MB for pseudo-closed


runs of this query. This size does not include storage used by MTIs.
Contains the null value if there are no prior runs.

340 IBM i: Performance and Query Optimization


Table 67. ACTIVE_QUERY_INFO table function (continued)

Column Name Data Type Description

AVERAGE_DATABASE_READS BIGINT The average number of asynchronous and synchronous database


reads for pseudo-closed runs of this query.
Contains the null value if there are no prior runs.

AVERAGE_PAGE_FAULTS BIGINT The average number of page faults for pseudo-closed runs of this
query.
Contains the null value if there are no prior runs.

Examples
• Retrieve information about all active SQE queries on the system.

SELECT *
FROM TABLE(QSYS2.ACTIVE_QUERY_INFO( ));

• Find which QZDASOINIT jobs are using MTIs.

SELECT JOB_NAME, MTI_COUNT, MTI_SIZE


FROM TABLE(QSYS2.ACTIVE_QUERY_INFO(
JOB_NAME => 'QZDASOINIT'))
WHERE MTI_COUNT > 0;

ADD_QUERY_THRESHOLD procedure
The ADD_QUERY_THRESHOLD procedure defines a new threshold to be used by the Query Supervisor.
Adding a threshold only affects subsequently executed queries. Queries that are currently running
continue to use the thresholds that were in effect when the query execution was initiated. The Query
Supervisor only supervises user jobs. It does not affect system jobs or queries run by the operating
system. The thresholds only apply to resources used by the SQL Query Engine (SQE).
Query Supervisor thresholds can include using job name, user name, and subsystem filters. The filters
are combined to restrict the set of jobs for the rule. For jobs that meet the filtering criteria, when
the threshold is met or exceeded, any exit programs registered with the QIBM_QQQ_QRY_SUPER exit
point are called. An exit program can be used to implement actions such as query logging or real-time
notification. It can also direct SQE to terminate the query. The exit program interface is described here:
Query Supervisor Exit Program.
When the first threshold is defined for a system, any active jobs, including the job that runs the initial
ADD_QUERY_THRESHOLD, will not be affected by Query Supervisor thresholds.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.

Database performance and query optimization 341


ADD_QUERY_THRESHOLD ( threshold-name ,
THRESHOLD_NAME =>

threshold-type ,
THRESHOLD_TYPE =>

threshold-value
THRESHOLD_VALUE =>

, job-names
JOB_NAMES =>

, include-users
INCLUDE_USERS =>

, exclude-users
EXCLUDE_USERS =>

, subsystems
SUBSYSTEMS =>

, detection-frequency
DETECTION_FREQUENCY =>

)
, long-comment
LONG_COMMENT =>

The schema is QSYS2.

threshold- A character or graphic string that provides a name for the threshold. The name can be up
name to 30 characters long and can contain any characters including blanks. The name cannot
be the same as an existing threshold name.
threshold- A character or graphic string that specifies the type of the threshold to be enforced.
type
CPU TIME The total processing unit time used by the query, in seconds.
ELAPSED TIME The total clock time, in seconds.
TEMPORARY STORAGE The amount of storage, in megabytes (MB), that the query
uses.
TOTAL IO COUNT The total number of I/O operations.

threshold- A big integer value that contains the threshold value, in units defined by the specified
value threshold-type. The value must be greater than 0.
job-names A character or graphic string that specifies up to 100 job names separated by either
a blank or a comma. Each job name can end with a wildcard character. For example,
'QPADEV*' indicates that any job name starting with the characters 'QPADEV' is a match.

342 IBM i: Performance and Query Optimization


Only jobs running with a matching job name are eligible to be supervised. Can contain the
following special value:

*ALL All jobs are supervised. This is the default.

include-users A character or graphic string that specifies up to 100 user names separated by either
a blank or a comma. A group profile does not expand to include all profiles that are
members of the group. Each name can end with a wildcard character. For example,
'ADM*' indicates that any user name starting with the characters 'ADM' is a match.
Queries where the effective user of the thread matches one of these names are eligible
to be supervised. If one or more names are specified for include-users, the exclude-users
parameter must have a value of *NONE. Can contain the following special value:

*ALL Jobs for all users are supervised. This is the default.

exclude- A character or graphic string that specifies up to 100 user names separated by either
users a blank or a comma. A group profile does not expand to include all profiles that are
members of the group. Each name can end with a wildcard character. For example,
'ADM*' indicates that any user name starting with the characters 'ADM' is a match.
Queries where the effective user of the thread matches one of these names are not
supervised. If one or more names are specified for exclude-users, the include-users
parameter must have a value of *ALL. Can contain the following special value:

*NONE No jobs are explicitly eliminated from being supervised based on the user
name. This is the default.

subsystems A character or graphic string that specifies up to 100 subsystem names separated by
either a blank or a comma. Each name can end with a wildcard character. For example,
'RSBS*' indicates that any subsystem name starting with the characters 'RSBS' is a
match.
Only jobs running in a subsystem that match one of these names are eligible to be
supervised. Can contain the following special value:

*ALL All jobs are supervised. This is the default.

detection- An integer value that specifies the minimum time, in seconds, between calls to exit
frequency programs registered with the QIBM_QQQ_QRY_SUPER exit point for this threshold for
a specific thread. During the detection-frequency time interval following a threshold
detection, the Query Supervisor does not process additional instances for this threshold
in the same thread. Each time a query is run in a thread, a specific threshold can be
processed at most once during the execution of that query.
The detection-frequency provides a protection from having a specific threshold
recognized and processed more frequently than desired. If the same threshold is
encountered within the same thread and the detection-frequency time period has not yet
completed, the associated exit programs are not called and there is no external evidence
that the Query Supervisor did not perform threshold detection.
The default is 600 (10 minutes).
long- A character or graphic string that describes this Query Supervisor threshold. It can be up
comment to 2000 characters long.

Examples
• Set a threshold value for total CPU time to 30 seconds for all jobs. When this value is reached, any
registered exit programs will be called.

CALL QSYS2.ADD_QUERY_THRESHOLD(THRESHOLD_NAME => 'MAXTIME',


THRESHOLD_TYPE => 'CPU TIME',

Database performance and query optimization 343


THRESHOLD_VALUE => 30,
LONG_COMMENT => 'Maximum runtime for all jobs');

• Set a threshold value for temporary storage to 10 megabytes for all jobs except for those running with
the BATCHRUN user profile. Set a detection frequency of 2 minutes. When the storage threshold value
is reached, any registered exit programs will be called. If the same thread reaches this threshold for a
different query within 2 minutes, the registered exit programs will not be called.

CALL QSYS2.ADD_QUERY_THRESHOLD(THRESHOLD_NAME => 'Temp storage',


THRESHOLD_TYPE => 'TEMPORARY STORAGE',
THRESHOLD_VALUE => 10,
EXCLUDE_USERS => 'BATCHRUN',
DETECTION_FREQUENCY => 120);

DATABASE_MONITOR_INFO view
The DATABASE_MONITOR_INFO view returns information about database monitors and plan cache event
monitors on the server. Database monitors are started using the Start Database Monitor (STRDBMON)
command. The QSYS2.START_PLAN_CACHE_EVENT_MONITOR procedure is used to start a plan cache
event monitor. SQL Performance Monitors within IBM i Navigator are synonymous with database monitors
and are included in this view.
Authorization: None required.
The following table describes the columns in the view. The system name is DBMON_INFO. The schema is
QSYS2.
Table 68. DATABASE_MONITOR_INFO view

System Column
Column Name Name Data Type Description

MONITOR_ID MONITOR_ID CHAR(10) The system-assigned monitor ID for this monitor.

MONITOR_TYPE MONTYPE VARCHAR(7) Type of monitor.

PUBLIC A monitor is considered public when the STRDBMON


JOB parameter indicates that jobs other than the
current job should be monitored. Public monitors
remain active until they are explicitly ended using the
End Database Monitor (ENDDBMON) command.

PRIVATE A private monitor occurs when the STRDBMON JOB


parameter indicates to monitor only the current job.
The monitor is ended as part of job termination
processing, if needed. Only a private monitor that is
active in the current connection will be returned.

EVENT An SQL plan cache event monitor intercepts plans as


they are moved from the plan cache into a database
monitor file.

MONITOR_STATUS STATUS VARCHAR(8) Status of this monitor.

ACTIVE Monitor is active.

INACTIVE For a PUBLIC or PRIVATE monitor, it is inactive and


can become ACTIVE. For an EVENT monitor, entries
are no longer being collected.

CLOSING The PUBLIC or PRIVATE monitor is not active or is in


the processing of ending. It is not known if the entry
can be reused for monitoring.

MONITOR_RECORD_TYPE RCDTYPE VARCHAR(6) Type of database records in this monitor.

DETAIL Both basic and detail database monitor records. An


EVENT monitor always has a value of DETAIL.

BASIC Only basic database monitor records

MONITOR_LIBRARY MONLIB VARCHAR(10) Library for this monitor.

MONITOR_FILE MONFILE VARCHAR(10) The file to which the database activity detail is written for this
monitor.

344 IBM i: Performance and Query Optimization


Table 68. DATABASE_MONITOR_INFO view (continued)

System Column
Column Name Name Data Type Description

MONITOR_MEMBER MONMBR VARCHAR(10) Member for this monitor.

IASP_NUMBER IASPNUMBER SMALLINT The independent auxiliary storage pool (IASP) number for the
monitor file.

MONITOR_MEMBER_OPTION MBROPT VARCHAR(7) Value used for the member replace option the last time this
monitor was started.
Nullable
• REPLACE
• ADD
Contains the null value for an EVENT monitor.

NUMBER_ROWS CARD BIGINT The number of rows in the database monitor file.

Nullable Contains the null value if information is not available.

DATA_SIZE SIZE BIGINT The total size, in bytes, of the database monitor file.

Nullable Contains the null value if information is not available.

MONITOR_JOB_FILTER JOB VARCHAR(32) Qualified job name for this monitor. For an EVENT monitor, this is
the job that started the monitor. Following the qualified job name
is the filter operator that applies to the job name. This is either *EQ
or *NE.
The special value of *ALL indicates all jobs on the system are
monitored. A generic name is allowed for both the job name and
the user name.

HOST_VARIABLE HOSTVAR VARCHAR(9) How host variables are handled in this database monitor.

Nullable BASIC Host variables are written in the QQQ3010


database monitor record.

SECURE No host variables are captured and no QQQ3010


record is written.

CONDENSED Host variable values are captured in the


QQQ1000 database monitor record in column
QQDBCLOB1. No QQQ3010 record is written.

Contains the null value for an EVENT monitor.

FORCE_RECORDS FRCRCD SMALLINT The number of records to be held in the buffer before forcing
the records to be written to the file when running with a private
Nullable monitor.
Contains the null value if the system calculates the value or for an
EVENT monitor.

RUN_THRESHOLD_FILTER RUNTHLD INTEGER The filtering threshold, in seconds, based on the estimated run
time of SQL statements in this monitor.
Nullable
Contains the null value if a run time threshold is not used for
filtering or for an EVENT monitor.

STORAGE_THRESHOLD_FILTER STGTHLD INTEGER The filtering threshold, in megabytes, based on the estimated
temporary storage usage of SQL statements in this monitor.
Nullable
Contains the null value if a temporary threshold is not used for
filtering or for an EVENT monitor.

INCLUDE_SYSTEM_SQL INCSYSSQL VARCHAR(3) Monitor includes records for system-generated SQL statements.

YES Monitor records are generated for both user-specified and


system-generated SQL statements.

NO Monitor records are generated for only user-specified SQL


statements.

INI For a PUBLIC or PRIVATE monitor, records are generated


based on the value of the SQL_DBMON_OUTPUT option in
the QAQQINI query options.

Database performance and query optimization 345


Table 68. DATABASE_MONITOR_INFO view (continued)

System Column
Column Name Name Data Type Description

FILE_FILTER FTRFILE VARCHAR(2728) A list of up to 10 qualified file references that are used for filtering.
Following each file name is the filter operator that applies to the
Nullable file name. This is either *EQ or *NE. When more than one file is
listed, a comma and a single blank separate the entries. Either the
file name or the library name can be a generic name.
A special value of *ALL for the file name indicates all files in the
library.
Contains the null value if no database files are used for filtering.

USER_FILTER FTRUSER VARCHAR(158) A list of up to 10 user profiles that are used for filtering. Following
each user profile name is the filter operator that applies to the
Nullable user profile. This is either *EQ or *NE. When more than one profile
is listed, a comma and a single blank separate the entries. A profile
name can be a generic name.
Contains the null value if the user profile is not used for filtering.

TCPIP_FILTER FTRINTNETA VARCHAR(254) The TCP/IP address or host name is used for filtering.

Nullable This is an IPv4, IPv6, or IP host domain name, or the special value
of *LOCAL.
Contains the null value if the TCP/IP address or host name is not
used for filtering or for an EVENT monitor.

LOCAL_PORT_FILTER FTRLCLPORT INTEGER Filtering is based on the local TCP/IP port number. Monitor records
will be created for TCP/IP database server jobs running on behalf
Nullable of the specified local TCP/IP port. Jobs named QRWTSRVR and
QZDASOINIT are examples of these server jobs.
The IBM i well defined port numbers are documented here: Port
numbers for host servers and server mapper.
Contains the null value if the port number is not used for filtering
or for an EVENT monitor.

QUERY_GOVERNOR_FILTER FTRQRYGOVR VARCHAR(11) The query governor is used for filtering.

Nullable ALL Monitor records will be collected when a query


governor limit is exceeded.

CONDITIONAL Monitor records will be conditionally collected


when a query governor limit is exceeded.

Contains the null value if the query governor is not used for
filtering or for an EVENT monitor.

CLIENT_ACCTNG_FILTER FTRCLTACG VARCHAR(128) The CURRENT CLIENT_ACCTNG special register is used for
filtering.
Nullable
Contains the null value if the CURRENT CLIENT_ACCTNG special
register is not used for filtering or for an EVENT monitor.

CLIENT_APPLNAME_FILTER FTRCLTAPP VARCHAR(128) The CURRENT CLIENT_APPLNAME special register is used for
filtering.
Nullable
Contains the null value if the CURRENT CLIENT_APPLNAME
special register is not used for filtering or for an EVENT monitor.

CLIENT_PROGRAMID_FILTER FTRCLTPGM VARCHAR(128) The CURRENT CLIENT_PROGRAMID special register is used for
filtering.
Nullable
Contains the null value if the CURRENT CLIENT_PROGRAMID
special register is not used for filtering or for an EVENT monitor.

CLIENT_USERID_FILTER FTRCLTUSR VARCHAR(128) The CURRENT CLIENT_USERID special register is used for
filtering.
Nullable
Contains the null value if the CURRENT CLIENT_USERID special
register is not used for filtering or for an EVENT monitor.

CLIENT_WRKSTNNAME_FILTER FTRCLTWS VARCHAR(128) The CURRENT CLIENT_WRKSTNNAME special register is used for
filtering.
Nullable
Contains the null value if the CURRENT CLIENT_WRKSTNNAME
special register is not used for filtering or for an EVENT monitor.

346 IBM i: Performance and Query Optimization


Table 68. DATABASE_MONITOR_INFO view (continued)

System Column
Column Name Name Data Type Description

SQL_CODE_FILTER FTRSQLCODE VARCHAR(7) How the SQLCODE result from a statement execution is used for
filtering.
Nullable
NONZERO Any SQL statement with an SQLCODE value that is
non-zero is included in the monitor.

ERROR Any SQL statement with an SQLCODE that is less


than zero is collected in the monitor.

WARNING Any SQL statement with an SQLCODE that is greater


than zero is collected in the monitor.

SQLCODE Any SQL statement with an SQLCODE that exactly


matches the value in the SQLCODE_VALUE column
is collected in the monitor.

Contains the null value if the SQLCODE for a statement is not used
for filtering or for an EVENT monitor.

SQLCODE_VALUE SQLCODEVAL INTEGER The positive or negative SQLCODE value to use for filtering.

Nullable Contains the null value if the SQL_CODE_FILTER column contains


a value other than SQLCODE.

Examples
Example 1: Get the MONITOR_ID for all the active PUBLIC monitors and the file names associated with
the MONITOR_IDs.

SELECT MONITOR_ID, MONITOR_LIBRARY, MONITOR_FILE


FROM QSYS2.DATABASE_MONITOR_INFO
WHERE MONITOR_STATUS = 'ACTIVE' AND
MONITOR_TYPE = 'PUBLIC'

Example 2: Find the active monitors that have outfiles larger than 1Gig.

SELECT MONITOR_LIBRARY, MONITOR_FILE, NUMBER_ROWS, DATA_SIZE


FROM QSYS2.DATABASE_MONITOR_INFO
WHERE MONITOR_STATUS = 'ACTIVE' AND
DATA_SIZE > 1073741824

Example 3: Find any active monitors that are filtering based upon a specific SQLCODE (FTRSQLCODE).

SELECT MONITOR_ID, MONITOR_LIBRARY, MONITOR_FILE, SQLCODE_VALUE


FROM QSYS2.DATABASE_MONITOR_INFO
WHERE MONITOR_STATUS = 'ACTIVE' AND
SQL_CODE_FILTER = 'SQLCODE'

Example 4: Get the MONITOR_ID for a user's SQL plan cache event monitor and use it to end the active
event monitor.

CALL QSYS2.END_PLAN_CACHE_EVENT_MONITOR (SELECT MONITOR_ID


FROM QSYS2.DATABASE_MONITOR_INFO
WHERE MONITOR_TYPE = 'EVENT' AND
MONITOR_LIBRARY = 'USERLIB')

HARVEST_INDEX_ADVICE procedure
The HARVEST_INDEX_ADVICE procedure generates one or more CREATE INDEX statements in source file
members for a specified table based on indexes that have been advised for the table.
Authorization: See Note below.

Database performance and query optimization 347


HARVEST_INDEX_ADVICE ( schema-name , table-name ,

times_advised , mti_used , average_estimate , output-library , output-file

The schema is SYSTOOLS.

schema-name A character string containing the system name of the schema containing the table.
table-name A character string containing the system name of the table.
times-advised The number of times an index should have been advised before creating a permanent
index. Pass a value of 1 to not limit index creation by the number of times advised.
mti-used The number of times a maintained temporary index (MTI) has been used because a
matching permanent index did not exist. Pass a value of 0 to not limit index creation
by MTI use.
average- The average estimated number of seconds needed to execute the query that drove
estimate the index advice. Pass a value of 0 to not limit index creation by the average query
estimate.
output-library A character string value containing the name of the library for the output source file.
output-file A character string value containing the name of the output source file. The file must
exist and must be a source physical file.

For each potential index meeting the specified criteria, a CREATE INDEX statement to create the
permanent index will be generated in a member in the source file provided to this procedure. A radix
index will be named name_RADIX_INDEX_n. An EVI index will be named name_EVI_INDEX_n. The
name represents the table name and n is a unique number. The row containing this advised index is
removed from the QSYS2.SYSIXADV table.

Note
This procedure is provided in the SYSTOOLS schema as an example of how to process index advice using
an SQL procedure. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can be
extracted and used as a model for building similar procedures, or to create a customized version within a
user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Harvest create index statements for file TOYSTORE/SALES into source physical file QGPL/INDEXSRC.
Then use RUNSQLSTM to create the indexes.

BEGIN
DECLARE NOT_FOUND CONDITION FOR '02000';
DECLARE ERROR_COUNT INTEGER DEFAULT 0;
DECLARE AT_END INT DEFAULT 0;
DECLARE V_INDEX_COUNT INTEGER DEFAULT 0;
DECLARE V_PARTITION_NAME VARCHAR(10);
DECLARE INDEX_SOURCE_CURSOR CURSOR FOR
SELECT TABLE_PARTITION FROM QSYS2.SYSPARTITIONSTAT
WHERE TABLE_SCHEMA = 'QGPL' AND TABLE_NAME = 'INDEXSRC';
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET ERROR_COUNT = ERROR_COUNT + 1;

CALL QSYS2.QCMDEXC('DLTF FILE(QGPL/INDEXSRC)');


CALL QSYS2.QCMDEXC('CRTSRCPF FILE(QGPL/INDEXSRC) RCDLEN(10000)');
-- Create the source file with a big record length,
-- to allow the create index statement to fit on one line
CALL SYSTOOLS.HARVEST_INDEX_ADVICE('TOYSTORE', 'SALES', 100, 50, 5, 'QGPL', 'INDEXSRC');

348 IBM i: Performance and Query Optimization


BEGIN
DECLARE V_RUNSQLSTM_TEXT VARCHAR(500);
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET AT_END = 1;
DECLARE CONTINUE HANDLER FOR NOT_FOUND SET AT_END = 1;
OPEN INDEX_SOURCE_CURSOR;
FETCH FROM INDEX_SOURCE_CURSOR INTO V_PARTITION_NAME;
WHILE ( AT_END = 0 ) DO
-- Now that QGPL/INDEXSRC has been populated with members named HARVnnnn,
-- the RUNSQLSTM command can be used to execute the CREATE INDEX statement.
-- By using ERRLVL = 30, we'll ignore any failures.
SET V_RUNSQLSTM_TEXT = 'RUNSQLSTM SRCFILE(QGPL/INDEXSRC) SRCMBR('
CONCAT RTRIM(V_PARTITION_NAME)
CONCAT ') COMMIT(*NONE) NAMING(*SQL) ERRLVL(30) MARGINS(10000)';
CALL QSYS2.QCMDEXC(V_RUNSQLSTM_TEXT);
FETCH FROM INDEX_SOURCE_CURSOR INTO V_PARTITION_NAME;
END WHILE;
CLOSE INDEX_SOURCE_CURSOR;
END;
END;

Related reference
SYSTOOLS
SYSTOOLS is a set of Db2 for IBM i supplied examples and tools.

MTI_INFO table function


The MTI_INFO table function returns information about Maintained Temporary Indexes (MTIs).

Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.

MTI_INFO (
table-schema
TABLE_SCHEMA =>

)
, table-name
TABLE_NAME =>

The schema is QSYS2.

table- A character or graphic string expression that contains the schema name of the base table
schema for the MTIs to be returned. The schema name may be either the SQL or the system schema
name.
Can contain the following special value:

*ALL Information for MTIs in all schemas with a base table specified by table-schema is
returned. This is the default.

If this parameter contains an empty string or the null value, *ALL is used.
table- A character or graphic string expression that contains the table name of the base table for
name the MTIs to be returned. The table name may be either the SQL or the system table name.
Can contain the following special value:

*ALL Information for all MTIs with a base table in table-schema is returned. This is the
default.

If this parameter contains an empty string or the null value, *ALL is used.

The result of the function is a table containing multiple rows with the format shown in the following table.
Each row contains information for one MTI on the system. All columns are nullable.

Database performance and query optimization 349


Table 69. MTI_INFO table function

Column Name Data Type Description

TABLE_SCHEMA VARCHAR(128) Schema name of the base table that the MTI is created over.

TABLE_NAME VARCHAR(128) Name of the base table that the MTI is created over.

REFERENCE_COUNT BIGINT The current number of references to this MTI. This includes plans in
the plan cache and open queries that are using this MTI. When this
count goes to 0, the MTI will be deleted.

KEYS INTEGER Number of keys.

KEY_DEFINITION DBCLOB(10000) CCSID 1200 Key definition.

STATE VARCHAR(20) The current state of the MTI.

CREATED MTI is in a valid state but has not been


populated. This can occur if the query subtree
that uses the MTI has not been run.

CREATING MTI is currently being created.

DELETING MTI is currently being deleted.

MAPPING ERROR A selection or mapping error occurred during


index build. A mapping or selection error
can occur if the key definition or the sparse
definition contains an expression and that
expression resulted in an error when being run.
An example of that is a divide by zero.

POPULATING The MTI is currently populating.

REBUILD The index portion of the MTI will need to be


REQUIRED re-populated on the next use of the MTI.

VALID MTI is in a valid state and populated.

nnnn A 4 digit number indicating an error status to be


used by IBM support.

MTI_SIZE BIGINT The current size of the MTI in bytes.

CREATE_TIME TIMESTAMP The timestamp of when the MTI was created.

LAST_BUILD_START_TIME TIMESTAMP Start of the last index build.


Contains the null value if the index portion of the MTI has not been
populated.

LAST_BUILD_END_TIME TIMESTAMP End of the last index build.


Contains the null value if the index portion of the MTI has not been
populated or is currently being populated.

REUSABLE VARCHAR(3) MTI is reusable across queries.

NO MTI can only be used for this query.

YES MTI is reusable.

SPARSE VARCHAR(3) MTI is sparse.

NO MTI is not sparse.

YES MTI is sparse.

SPARSE_DEFINITION DBCLOB(10000) CCSID 1200 The predicate used to create the sparse MTI.
Contains the null value if SPARSE is NO.

QRO_HASH VARCHAR(8) An internally generated identifier which identifies the SQE query which
originally created the MTI.

PLAN_IDENTIFIER DECIMAL(20,0) Identifies the plan within the plan cache which originally created the
MTI.

USER_NAME VARCHAR(10) The effective user of the thread that created the MTI.

QUALIFIED_JOB_NAME VARCHAR(28) The fully qualified job name of the job that created the MTI.

JOB_NAME VARCHAR(10) The name of the job.

JOB_USER VARCHAR(10) The user profile that started the job.

350 IBM i: Performance and Query Optimization


Table 69. MTI_INFO table function (continued)

Column Name Data Type Description

JOB_NUMBER VARCHAR(6) The job number of the job.

MTI_NAME VARCHAR(128) A generated name that identifies the MTI.

LIBRARY_NAME VARCHAR(10) The name of the library that contains FILE_NAME.

FILE_NAME VARCHAR(10) The database file name of the base table that the MTI is created over.

Example
• Return information about all MTIs that exist over the APPLIB/EMPLOYEE table.

SELECT * FROM TABLE(QSYS2.MTI_INFO('APPLIB', 'EMPLOYEE'));

QUERY_SUPERVISOR view
The QUERY_SUPERVISOR view contains the threshold rules defined for the Query Supervisor.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.
The following table describes the columns in the view. The system name is QRY_SUPER. The schema is
QSYS2.
Table 70. QUERY_SUPERVISOR view

Column Name System Column Name Data Type Description

THRESHOLD_NAME NAME VARGRAPHIC(30) The name of the threshold.

CCSID 1200

THRESHOLD_TYPE TYPE VARCHAR(30) The type of threshold

CPU TIME The total processing unit


time used by the query, in
seconds.

ELAPSED TIME The total clock time, in


seconds.

TEMPORARY The amount of storage, in


STORAGE megabytes (MB), that the
query uses.

TOTAL IO COUNT The total number of I/O


operations.

THRESHOLD_VALUE VALUE BIGINT The value associated with THRESHOLD_TYPE, in


the appropriate units.

JOB_NAMES JOB_NAMES VARCHAR(1099) A list of job names supervised by this threshold.


Each name in the list is padded with blanks to fill
Nullable ten characters, with a single comma separating
the name entries.
Contains the null value if all job names are
supervised.

INCLUDE_USERS INCL_USERS VARCHAR(1099) A list of user names supervised by this threshold.


Each name in the list is padded with blanks to fill
Nullable ten characters, with a single comma separating
the name entries.
Contains the null value if all user names are
supervised.

EXCLUDE_USERS EXCL_USERS VARCHAR(1099) A list of user names that are not supervised by
this threshold. Each name in the list is padded
Nullable with blanks to fill ten characters, with a single
comma separating the name entries.
Contains the null value if no user names are
excluded.

Database performance and query optimization 351


Table 70. QUERY_SUPERVISOR view (continued)

Column Name System Column Name Data Type Description

SUBSYSTEMS SUBSYSTEMS VARCHAR(1099) A list of subsystems supervised by this threshold.


Each name in the list is padded with blanks to fill
Nullable ten characters, with a single comma separating
the name entries.
Contains the null value if all subsystems are
supervised.

DETECTION_FREQUENCY FREQUENCY INTEGER The minimum frequency, in seconds, that a


notification is sent for this threshold within a
specific thread. During the time interval following
a threshold detection, the Query Supervisor
does not process additional instances for this
threshold, in the same thread. Each time a query
is run in a thread, a specific threshold can be
processed at most once during the execution of
that query.
The detection-frequency value provides a
protection from having a specific threshold
recognized and processed more frequently than
desired. If the same threshold is encountered
within the same thread and the detection-
frequency time period has not yet completed, the
associated exit programs are not called and there
is no external evidence that the Query Supervisor
did not perform threshold detection.

LONG_COMMENT REMARKS VARGRAPHIC(2000) Description of this threshold rule.

CCSID 1200 Contains the null value if the rule has no


Nullable descriptive text.

Example
• List all the thresholds defined for the Query Supervisor.

SELECT *
FROM QSYS2.QUERY_SUPERVISOR ORDER BY THRESHOLD_TYPE, THRESHOLD_VALUE DESC;

REMOVE_INDEXES procedure
The REMOVE_INDEXES procedure drops any indexes meeting the specified criteria.
Authorization: See Note below.

REMOVE_INDEXES ( schema-name , times_used , index-age )

The schema is SYSTOOLS.

schema-name A character string containing the system name of the schema containing the indexes to
be evaluated. If the NULL value is passed, the entire database is processed.
times_used A big integer value indicating the number of times an index has been used.
index-age A character string containing an SQL labeled duration, such as '2 MONTHS'.

The procedure will evaluate all indexes for the specified schema-name value and drop any index that does
not meet the times-used and index-age threshold. If the number of times the index has been used by a
query and used for statistics is less than the times-used value, the index is considered under utilized and
is a candidate to be dropped. An index that has existed at least the length of time indicated by index-age
is also a candidate to be dropped. Any index that meets both criteria is dropped.
Only index names that have names like name_RADIX_INDEX_x or name_EVI_INDEX_x will be
considered by this procedure.

352 IBM i: Performance and Query Optimization


Note
This procedure is provided in the SYSTOOLS schema as an example of how to prune indexes using
an SQL procedure. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can be
extracted and used as a model for building similar procedures, or to create a customized version within a
user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Examples
• Remove any index in MYLIB that is older than a month that has never been used.

CALL SYSTOOLS.REMOVE_INDEXES('MYLIB', 1, '1 MONTH')

• Remove all indexes from all schemas on the system that have existed for at least two weeks and haven't
been used at least 100 times.

CALL SYSTOOLS.REMOVE_INDEXES(NULL, 100, '14 DAYS')

Related reference
SYSTOOLS
SYSTOOLS is a set of Db2 for IBM i supplied examples and tools.

REMOVE_QUERY_THRESHOLD procedure
The REMOVE_QUERY_THRESHOLD procedure removes a threshold that is monitored by the Query
Supervisor. Removing a threshold only affects subsequently executed queries. Queries that are currently
running will continue to use the thresholds that were in effect when the query execution was initiated.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.

REMOVE_QUERY_THRESHOLD ( threshold-name )
THRESHOLD_NAME =>

The schema is QSYS2.

threshold-name A character or graphic string that specifies the name of an existing threshold to be
removed.

Example
Remove the MAXTIME threshold rule.

CALL QSYS2.REMOVE_QUERY_THRESHOLD(THRESHOLD_NAME => 'MAXTIME');

RESET_TABLE_INDEX_STATISTICS procedure
The RESET_TABLE_INDEX_STATISTICS procedure clears usage statistics for indexes defined over a table
or tables and optionally deletes rows from the index advice tracking table.
Authorization: The counts will only be reset when the caller has *OBJMGT and *OBJOPR authority on the
table. For each index found over the table, *OBJOPR authority to the index is required. If the caller does
not have the required authority to the table, the object is skipped and no warning is returned. If the caller
does not have the required authority to the index, the object is skipped and an SQL warning is returned.

Database performance and query optimization 353


To delete index advice, the DELETE privilege is required on QSYS2/SYSIXADV. Index advice is only deleted
when the caller has the required authority to the table and index.

RESET_TABLE_INDEX_STATISTICS ( schema-name ,
SCHEMA_NAME =>

table-name
TABLE_NAME =>

)
, delete-advice
DELETE_ADVICE =>

The schema is QSYS2.


This procedure will zero the QUERY_USE_COUNT and QUERY_STATISTICS_COUNT usage statistics for all
indexes over the specified tables. These counts can also be reset using the Change Object Description
(CHGOBJD) CL command, but the command requires an exclusive lock.

schema- A character string expression for the name of the schema or schemas to use. The name
name is case-sensitive and must not be delimited. Wildcard characters (_ and %) are allowed in
the string following the rules for the SQL LIKE predicate.
table-name A character string expression for the name of the table or tables to use. The name is
case-sensitive and must not be delimited. Wildcard characters (_ and %) are allowed in
the string following the rules for the SQL LIKE predicate.
delete- A character string expression that indicates whether this procedure should remove rows
advice from the index advice tracking table.

NO Index advice for the table is not affected. This is the default.
YES This procedure will delete rows from the index advice tracking table (QSYS2/
SYSIXADV) that correspond to schema-name and table-name. To be removed, an
index must exist and the user must be authorized to the index.

The procedure writes information related to every index processed into an SQL global temporary table.
The fields LAST_QUERY_USE, LAST_STATISTICS_USE, LAST_USE_DATE, and NUMBER_DAYS_USED are
not affected. The following query will display the results of the last call to the procedure:
SELECT * FROM SESSION.SQL_INDEXES_RESET
The table that is created contains the following columns:
Table 71. SQL_INDEXES_RESET result table

Column Name System Column Name Data Type Description

TABLE_SCHEMA DBNAME VARCHAR(128) Schema name of table.

TABLE_NAME NAME VARCHAR(128) Name of table.

TABLE_PARTITION TABLE00001 VARCHAR(128) Name of the table partition or member.

PARTITION_TYPE PARTI00001 CHAR(1) The type of table partitioning.

PARITION_NUMBER PARTI00002 INTEGER The partition number of this partition.

NUMBER_DISTRIBUTED_PARTITIONS NUMBE00001 INTEGER If the table is a distributed table, contains the total number of
partitions.

INDEX_SCHEMA INDEX00001 VARCHAR(128) Schema name of index.

INDEX_NAME INDEX_NAME VARCHAR(128) Name of index.

INDEX_MEMBER INDEX00002 VARCHAR(128) Partition or member name of index.

INDEX_TYPE INDEX_TYPE CHAR(11) Type of index.

354 IBM i: Performance and Query Optimization


Table 71. SQL_INDEXES_RESET result table (continued)

Column Name System Column Name Data Type Description

LAST_QUERY_USE LAST_00002 TIMESTAMP The timestamp of the last time the SQL index was used in a query
since the last time the usage statistics were reset.

LAST_STATISTICS_USE LAST_00003 TIMESTAMP The timestamp of the last time the SQL index was used by the
optimizer for statistics since the last time the usage statistics
were reset.

QUERY_USE_COUNT QUERY00001 BIGINT The number of times the SQL index was used in a query since the
last time the usage statistics were reset.

QUERY_STATISTICS_COUNT QUERY00002 BIGINT The number of times the SQL index was used by the optimizer for
statistics since the last time the usage statistics were reset.

SYSTEM_TABLE_SCHEMA SYS_DNAME CHAR(10) System table schema name.

SYSTEM_TABLE_NAME SYS_TNAME CHAR(10) System table name.

SYSTEM_TABLE_MEMBER SYSTE00001 CHAR(10) System member name.

Examples
• Zero the statistics for all indexes over table TOYSTORE.SALES

CALL QSYS2.RESET_TABLE_INDEX_STATISTICS ('TOYSTORE', 'SALES')

• Zero the statistics for all indexes over any table in schema TOYSTORE whose name starts with the letter
S.

CALL QSYS2.RESET_TABLE_INDEX_STATISTICS ('TOYSTORE', 'S%')

Plan Cache Services


These services include procedures to assist you in performing database administration (DBA) and
database engineering (DBE) tasks.
These procedures allow for programmatic access to the SQL plan cache and can be used for tasks such as
scheduling plan cache captures or pre-starting an event monitor.

CHANGE_PLAN_CACHE_SIZE procedure
The CHANGE_PLAN_CACHE_SIZE procedure provides a way to change the maximum amount of storage
used by the plan cache.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.

CHANGE_PLAN_CACHE_SIZE ( integer-expression )

The schema is QSYS2.

integer- A numeric expression that specifies the size, in megabytes, that the plan cache cannot
expression exceed. Once set, the maximum size of the plan cache will be retained across IPLs and
IBM i operating system upgrades. If the value is zero, the plan cache is reset to its default
value which allows the plan cache to be auto-sized by the database.

Example
• Change the plan cache maximum size to 3072 megabytes:

CALL QSYS2.CHANGE_PLAN_CACHE_SIZE(3072);

Database performance and query optimization 355


CLEAR_PLAN_CACHE procedure
The CLEAR_PLAN_CACHE procedure either clears all plans or removes the specified plans from the SQL
plan cache without requiring a system IPL.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.

CLEAR_PLAN_CACHE (

qro-hash
QRO_HASH => , plan-identifier
PLAN_IDENTIFIER =>

The schema is QSYS2.

qro-hash A character or graphic string expression that identifies a set of plans for a specific SQE
query. If qro-hash is not specified, the null value is used.
plan-identifier A numeric value which uniquely identifies a plan within the plan cache. If plan-identifier
is not specified, the null value is used.

If qro-hash is specified and plan-identifier is not specified, the procedure will clear all the plans from the
SQL plan cache with that qro-hash. If a qro-hash and a plan-identifier are specified, that specific plan will
be removed. If no matching plan is found, the procedure returns without error.
If no parameters are specified, or a null value is specified for both qro-hash and plan-identifier, the
procedure will clear all plans in the SQL plan cache that exist at the time the procedure is run.
Besides clearing the plan information, any Maintained Temporary Indexes (MTIs) not currently in use by a
query will be deleted as part of the clear operation. Queries run while the CLEAR_PLAN_CACHE procedure
is running may have their plans removed, but the queries themselves will not incur a failure related to plan
removal. After the clear is complete, as queries are re-optimized, they will be inserted into the plan cache.
Removal of all plans is intended for use primarily in performance test and quality assurance
environments. It provides database performance analysts with a way to create a consistent environment
from which to evaluate potential database performance changes.
Removal of a specific plan is intended for limited use, such as when directed by IBM service or when
needing to force the optimizer to re-optimize a specific query.
The time the CLEAR_PLAN_CACHE procedure takes to run will vary depending on the plan cache size. To
avoid tying up an interactive job, it is recommended that the procedure should be submitted in a batch job
using a combination of the Submit Job (SBMJOB) and Run SQL (RUNSQL) CL commands.

Notes
The QRO hash is an internally generated identifier for an SQE query. In general, this identifier will be
unique for each SQE query and uses implicit schema qualification among other data to generate the QRO
hash. If the SQE optimizer generates multiple plans for the same query, then multiple plans will have the
same QRO hash. However, every plan will have a unique plan identifier. The QRO hash for a statement may
change on release boundaries or after loading PTFs. The QRO hash is externalized:
• In a Visual Explain
• From Show Statements exploration of the SQL Plan Cache and SQL Plan Cache Snapshots
• In the QQC83 column of the 3014 record of a database monitor or plan cache snapshot file
• As information passed to a Query Supervisor exit program.
• As returned from the QSYS2.ACTIVE_JOB_INFO table function

356 IBM i: Performance and Query Optimization


The plan identifier is a unique number that is generated when the plan is optimized. The plan identifier is
externalized:
• The statement number of a Visual Explain of a plan cache snapshot or a Visual Explain from the Show
Statements exploration of the SQL Plan Cache
• From Show Statements exploration of the SQL Plan Cache and SQL Plan Cache Snapshots
• In the QQUCNT column of the 1000 record of a plan cache snapshot file.
• As information passed to a Query Supervisor exit program.

Example
• Submit a job to clear the plan cache.

SBMJOB CMD(RUNSQL SQL('CALL QSYS2.CLEAR_PLAN_CACHE()') COMMIT(*NONE) NAMING(*SQL))

• Clear all plans that have a QRO hash of 'D0C257FD'.

CALL QSYS2.CLEAR_PLAN_CACHE(QRO_HASH => 'D0C257FD');

• Clear one specific plan.

CALL QSYS2.CLEAR_PLAN_CACHE(QRO_HASH => '1239A9F0',


PLAN_IDENTIFIER => 1305582);

DUMP_PLAN_CACHE procedure
The DUMP_PLAN_CACHE procedure creates a database monitor file (snapshot) from the plan cache.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.

DUMP_PLAN_CACHE ( library-name ,
FILESCHEMA =>

file-name
FILENAME =>

, plan-identifier
PLAN_IDENTIFIER =>

, sql-statement-text-filter
SQL_STATEMENT_TEXT_FILTER =>

, include-system-queries
INCLUDE_SYSTEM_QUERIES =>

)
, iasp-name
IASP_NAME =>

The schema is QSYS2.

library-name A character or graphic string expression that identifies the name of the library
containing file-name. The special value of *CURLIB can be used.

Database performance and query optimization 357


file-name A character or graphic string expression that identifies the name of the resulting
database monitor file. If the file does not exist, it is created. If the file exists, the new
plan cache snapshot will be appended to it.
plan-identifier A numeric value which uniquely identifies a plan within the plan cache. When a plan-
identifier is specified, sql-statement-text-filter, include-system-queries, and iasp-name
are ignored. *SYSBAS and all available IASPs are searched for the plan-identifier.
sql-statement- A character or graphic string expression that identifies a substring of text that must
text-filter match for a plan to be selected. The comparison is case insensitive. Blanks, control
characters, and comments embedded in the statement text are significant.
If this parameter it not provided, plans are not filtered by statement text.
include- A character or graphic string expression that indicates whether system queries are
system-queries dumped in addition to user queries.

NO Only user queries are dumped. This is the default.


YES System queries and user queries are dumped.

iasp-name A character or graphic string expression that identifies the independent ASP (IASP)
group to be used for finding plans to dump. An IASP must be available to access its
plans.

name The name of the IASP containing plans to dump.


*ALL Plans from SYSBASE and all available IASPs are dumped.
*CURRENT Only plans in the current IASP are dumped. This is the default.
*SYSBAS Only plans in SYSBASE are dumped.

If plan-identifier is specified, only that specific plan is dumped. If plan-identifier is not specified, all plans
in the plan cache matching sql-statement-text-filter and include-system-queries that are found in the IASP
identified by iasp-name are dumped.
The file has the same definition as the QSYS/QAQQDBMN file. See Database monitor SQL table format for
more information.
If the file already exists, the authorities are not changed. If the file does not exist, it is created, and
ownership of the file is assigned to the effective user of the thread that calls DUMP_PLAN_CACHE. The
public authority is set to *EXCLUDE. All other authorities are copied from the QSYS/QAQQDBMN file.
The time the DUMP_PLAN_CACHE procedure takes to run will vary depending on the plan cache size. To
avoid tying up an interactive job, it is recommended that the procedure should be submitted in a batch job
using a combination of the Submit Job (SBMJOB) and Run SQL (RUNSQL) CL commands.

Notes
The plan identifier is a unique number that is generated when the plan is optimized. The plan identifier is
externalized in several ways:
• The statement number of a Visual Explain of a plan cache snapshot or a Visual Explain from the Show
Statements exploration of the SQL Plan Cache
• From Show Statements exploration of the SQL Plan Cache and SQL Plan Cache Snapshots
• In the QQUCNT column of the 1000 record of a plan cache snapshot file.
• As information passed to a Query Supervisor exit program.

Example
• Dump the plan cache to a database performance monitor file called SNAPSHOT1 in library SNAPSHOTS.

358 IBM i: Performance and Query Optimization


CALL QSYS2.DUMP_PLAN_CACHE('SNAPSHOTS','SNAPSHOT1');

• Dump a specific plan to a database performance monitor file called QUERY1 in library SNAPSHOTS.

CALL QSYS2.DUMP_PLAN_CACHE('SNAPSHOTS','QUERY1', 126783);

• Dump all plans in the current IASP that reference table TOYSTORE_SALES.

CALL QSYS2.DUMP_PLAN_CACHE(FILESCHEMA => 'SNAPSHOTS',


FILENAME => 'SALES',
SQL_STATEMENT_TEXT_FILTER => 'TOYSTORE_SALES');

• Dump all plans in *SYSBAS that reference table TOYSTORE_SALES.

CALL QSYS2.DUMP_PLAN_CACHE(FILESCHEMA => 'SNAPSHOTS',


FILENAME => 'SALES',
SQL_STATEMENT_TEXT_FILTER => 'TOYSTORE_SALES',
IASP_NAME => '*SYSBAS');

DUMP_PLAN_CACHE_PROPERTIES procedure
The DUMP_PLAN_CACHE_PROPERTIES creates a file containing the properties of the plan cache.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.

DUMP_PLAN_CACHE_PROPERTIES ( library-name , file-name )

The schema is QSYS2.

library- A character or graphic string expression that identifies the name of the library containing
name file-name.
file-name A character or graphic string expression that identifies the name of the resulting properties
file. It must be a valid system file name. If the file does not exist, it is created with public
authority for the file the same as the create authority specified for the library in which
the file is created. Use the QSYS2.LIBRARY_INFO table function or the Display Library
Description (DSPLIBD) command to show the library's create authority. If the file exists, the
new plan cache properties will be appended to it.

The file definition matches the definition of QSYS2/QDBOPPCGEN, which has the following definition.
Table 72. QDBOPPCGEN table

Column Name System Column Name Data Type Description

HEADING HEADING VARCHAR(128) Description of the value for this row.

VALUE VALUE VARCHAR(128) The current value of the item.

VALUE_UNITS VALUEUNITS VARCHAR(128) The type of unit that applies to the VALUE columns.

MB The number is in megabytes.

% The number represents a percentage.

If there is no unit, the value is a single blank.

ENTRY_NUMBER ENTRYNBR INTEGER A unique identifying number for this row. The number assigned
to a value will be the same in every generated plan cache
properties file.

ENTRY_TYPE ENTRY_TYPE CHAR(2) The type of entry.

DA Detail entry

HE Heading entry

AD Modifiable detail entry

GRAPHABLE GRAPHABLE CHAR(1) The data value is meaningful to be graphed.

Database performance and query optimization 359


Table 72. QDBOPPCGEN table (continued)

Column Name System Column Name Data Type Description

MINVALUE MINVALUE VARCHAR(128) The minimum value allowed for this item

MAXVALUE MAXVALUE VARCHAR(128) The maximum value allowed for this item.

DFTVALUE DFTVALUE VARCHAR(128) The initial value provided by the system for this value.

CHANGE_WARNING CHGWARN VARCHAR(512) Not used.

Example
• Dump the plan cache properties to a file called PCPROP1 in library SNAPSHOTS.

CALL QSYS2.DUMP_PLAN_CACHE_PROPERTIES('SNAPSHOTS','PCPROP1');

DUMP_PLAN_CACHE_TOPN procedure
The DUMP_PLAN_CACHE_TOPN procedure creates a database monitor file (snapshot) from the plan
cache containing the user-initiated queries based on the specified category option.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.

DUMP_PLAN_CACHE_TOPN ( library-name ,
FILESCHEMA =>

file-name , topn_number
FILENAME => TOPN =>

)
, category
CATEGORY =>

The schema is QSYS2.

library- A character or graphic string expression that identifies the name of the library containing
name file-name.
file-name A character or graphic string expression that identifies the name of the resulting database
monitor file. If the file does not exist, it is created. If the file exists, the new plan cache
properties will be appended to it.
topn- An integer expression representing the number of queries to dump
number
category A character or graphic string expression that identifies the type of top N queries to be
dumped.

CPU Dump the TOPN queries with the most accumulated CPU time.
DATABASE READS Dump the TOPN queries with the most accumulated database read
I/Os. This includes both synchronous and asynchronous reads.
RUNTIME Dump the TOPN queries with the longest accumulated runtime. This
is the default.
STORAGE Dump the TOPN queries with the largest temporary storage usage.

The file has the same definition as the QSYS/QAQQDBMN file. If the file does not exist, it is created with
the public authority set to *EXCLUDE. See Database monitor SQL table format for more information.

360 IBM i: Performance and Query Optimization


Example
• Capture the 20 queries with the largest elapsed time and dump the details into a snapshot file named
SNAPSHOTS/TOPN121413

CALL QSYS2.DUMP_PLAN_CACHE_TOPN('SNAPSHOTS', 'TOPN121413', 20);

DUMP_SNAP_SHOT_PROPERTIES procedure
The DUMP_SNAP_SHOT_PROPERTIES returns a result set containing the properties for an existing plan
cache snapshot.
Authorization: None required.

DUMP_SNAP_SHOT_PROPERTIES ( library-name , file-name )

The schema is QSYS2.

library-name A character or graphic string expression that identifies the name of the library containing
file-name.
file-name A character or graphic string expression that identifies the name of an existing database
monitor file.

The result set has the following definition.


Column Name Data Type Description

HEADING VARCHAR(128) Description of the value for this row.

VALUE VARCHAR(128) The current value of the item.

VALUE_UNITS VARCHAR(128) The type of unit that applies to the VALUE column.

MB The number is in megabytes.

Returns null if no unit applies.

ENTRY_NUMBER INTEGER A unique identifying number for this row. The number assigned to a value will be the
same in every generated plan cache properties file.

ENTRY_TYPE CHAR(2) The type of entry.

DA Detail entry

HE Heading entry

AD Modifiable detail entry

Example
• Return the plan cache properties of an existing snapshot.

CALL QSYS2.DUMP_SNAP_SHOT_PROPERTIES('SNAPSHOTS', 'TOPN121413');

END_ALL_PLAN_CACHE_EVENT_MONITORS procedure
The END_ALL_PLAN_CACHE_EVENT_MONITORS procedure ends all active plan cache event monitors.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.

END_ALL_PLAN_CACHE_EVENT_MONITORS ( )

The schema is QSYS2.

Example

Database performance and query optimization 361


• End all active plan cache event monitors:

CALL QSYS2.END_ALL_PLAN_CACHE_MONITORS();

END_PLAN_CACHE_EVENT_MONITOR procedure
The END_PLAN_CACHE_EVENT_MONITOR procedure ends the event monitor identified by the given
monitor-ID.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.

END_PLAN_CACHE_EVENT_MONITOR ( monitor-ID )

The schema is QSYS2.

monitor-ID A character or graphic string expression that identifies the monitor to be ended.

Example
• End the plan cache monitor identified by PLANCACHE1.

CALL QSYS2.END_PLAN_CACHE_EVENT_MONITOR('PLANC00001');

IMPORT_PC_EVENT_MONITOR procedure
The IMPORT_PC_EVENT_MONITOR procedure imports an event monitor file for usage in the SQL
Performance Center that is part of IBM i Access Client Solutions (ACS).
Authorization: The caller must have:
• *EXECUTE authority to the library, and
• *OBJOPR and *READ authorities to the event monitor file.

IMPORT_PC_EVENT_MONITOR ( library-name ,
PLAN_CACHE_LIBRARY =>

file-name ,
PLAN_CACHE_FILE => IMPORTED_NAME =>

imported-name )

The schema is QSYS2.

library-name A character or graphic string expression that identifies the name of the library
containing file-name.
file-name A character or graphic string expression that identifies the name of an existing event
monitor file.
imported-name The name of the plan cache event monitor to import. This name is used to identify the
plan cache event monitor in the SQL Performance Center.

Example
• Import a plan cache event monitor SNAPSHOTS/MON1 and name it NEWMON.

CALL QSYS2.IMPORT_PC_EVENT_MONITOR('SNAPSHOTS','MON1','NEWMON');

362 IBM i: Performance and Query Optimization


IMPORT_PC_SNAPSHOT procedure
The IMPORT_PC_SNAPSHOT procedure imports a plan cache snapshot file for usage in the SQL
Performance Center that is part of IBM i Access Client Solutions (ACS).
Authorization: The caller must have:
• *EXECUTE authority to the library, and
• *OBJOPR and *READ authorities to the event monitor file.

IMPORT_PC_SNAPSHOT ( library-name ,
PLAN_CACHE_LIBRARY =>

file-name ,
PLAN_CACHE_FILE => IMPORTED_NAME =>

imported-name )

The schema is QSYS2.

library-name A character or graphic string expression that identifies the name of the library
containing file-name.
file-name A character or graphic string expression that identifies the name of an existing plan
cache snapshot file.
imported-name The name of the plan cache snapshot to import. This name is used to identify the plan
cache snapshot in the SQL Performance Center.

Example
• Import a plan cache snapshot file SNAPSHOTS/SNAP121413.

CALL QSYS2.IMPORT_PC_SNAPSHOT('SNAPSHOTS','SNAP121413','Snapshot captured on 12/14/2013');

REMOVE_PC_EVENT_MONITOR procedure
The REMOVE_PC_EVENT_MONITOR procedure deletes a file containing an event monitor.
Authorization: The caller must have:
• *USE authority to the library, and
• *OBJOPR and *OBJEXIST authorities to the event monitor file.

REMOVE_PC_EVENT_MONITOR ( library-name
PLAN_CACHE_LIBRARY =>

, file-name )
PLAN_CACHE_FILE =>

The schema is QSYS2.

library-name A character or graphic string expression that identifies the name of the library containing
file-name.
file-name A character or graphic string expression that identifies the name of an existing event
monitor file.

Example

Database performance and query optimization 363


• Remove the plan cache event monitor PRUNEDP1 in SNAPSHOTS.

CALL QSYS2.REMOVE_PC_EVENT_MONITOR('SNAPSHOTS','PRUNEDP1');

REMOVE_PC_SNAPSHOT procedure
The REMOVE_PC_SNAPSHOT procedure deletes a file containing a plan cache snapshot.
Authorization: The caller must have:
• *USE authority to the library, and
• *OBJOPR and *OBJEXIST authorities to the performance monitor file and any dependent indexes.

REMOVE_PC_SNAPSHOT ( library-name , file-name )

The schema is QSYS2.

library-name A character or graphic string expression that identifies the name of the library containing
file-name.
file-name A character or graphic string expression that identifies the name of an existing plan cache
snapshot file.

Example
• Remove the plan cache snapshot file called PC1 in library SNAPSHOTS.

CALL QSYS2.REMOVE_PC_SNAPSHOT('SNAPSHOTS','PC1');

REMOVE_PERFORMANCE_MONITOR procedure
The REMOVE_PERFORMANCE_MONITOR procedure deletes a file containing a performance monitor.
Authorization: The caller must have:
• *USE authority to the library, and
• *OBJOPR and *OBJEXIST authorities to the performance monitor file and any dependent indexes.

REMOVE_PERFORMANCE_MONITOR ( library-name , file-name )

The schema is QSYS2.

library-name A character or graphic string expression that identifies the name of the library containing
file-name.
file-name A character or graphic string expression that identifies the name of an existing
performance monitor file.

Example
• Remove the performance monitor MON1 in SNAPSHOTS.

CALL QSYS2.REMOVE_PERFORMANCE_MONITOR('SNAPSHOTS','MON1');

START_PLAN_CACHE_EVENT_MONITOR procedure
The START_PLAN_CACHE_EVENT_MONITOR procedure starts an event monitor to capture plans as they
are removed from the cache and generates performance information into a database monitor file.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM function usage ID.

364 IBM i: Performance and Query Optimization


START_PLAN_CACHE_EVENT_MONITOR ( library-name , file-name

)
, monitor-ID

The schema is QSYS2.

library-name A character or graphic string expression that identifies the name of the library to contain
file-name. library-name cannot be QTEMP.
file-name A character or graphic string expression that identifies the name of the database monitor
file. It must be a valid system file name. If the file does not exist, it is created.
Initially the file is created and populated with the starting record id 3018 (column QQRID
= 3018).
monitor-ID An optional character string output variable that will contain the 10 character identifier of
the event monitor that was started.

The event monitor stays active until one of the following occurs:
• It is ended by one of the end event monitor procedure calls.
• It is ended using the IBM i Navigator interface.
• An IPL of the system occurs.
• The specified database monitor file is deleted or otherwise becomes unavailable.

Example
• Start an event monitor and place plan information into a database monitor file called PRUNEDP1 in
library SNAPSHOTS:

CALL QSYS2.START_PLAN_CACHE_EVENT_MONITOR('SNAPSHOTS','PRUNEDP1');

• Start an event monitor and place plan information into a database monitor file called PRUNEDPLANS1 in
library SNAPSHOTS. Capture the monitor id into host variable HVmonid for use later:

CALL QSYS2.START_PLAN_CACHE_EVENT_MONITOR('SNAPSHOTS','PRUNEDPLANS1',:HVmonid);

Utility Services
These procedures provide interfaces to monitor and work with SQL in jobs on the current system or to
compare constraint and routine information across systems.

ANALYZE_CATALOG table function


The ANALYZE_CATALOG table function returns one row for each inconsistency it finds in the database
catalog.
If no rows are returned, no inconsistencies were identified. Multiple rows can be returned for the same
object.
Authorization: The caller must have *ALLOBJ special authority.

Database performance and query optimization 365


ANALYZE_CATALOG (
option
OPTION =>

)
, library-name
LIBRARY_NAME =>

The schema is QSYS2.

option A character or graphic string expression that identifies the type of catalog analysis to
perform.

DBXREF Analysis will be done for objects in the database cross reference files. This is
the default.
Verification is done for constraints defined for *FILE objects.
The analysis done by this function goes beyond what RCLDBXREF
OPTION(*CHECK) provides. It verifies that the constraint definitions in every
database file object are correctly recorded in the database catalog.
DBXREF Analysis will be done of the database cross reference servers. The database
SERVER cross reference servers will be verified to ensure they are functioning properly.
One or more result rows with DBXREF SERVER in the CATEGORY column
indicate the current database cross reference server status.

library- A character or graphic string expression that identifies the library to be analyzed. This
name parameter only applies when option is DBXREF.

*ALL All *FILE objects within all libraries will be analyzed, including any in independent
auxiliary storage pools that are accessible. This is the default.
name All *FILE objects within this library will be analyzed.

The result of the function is a table containing one row for each reported item with the format shown in
the following table. All the columns are nullable.
Table 73. ANALYZE_CATALOG table function

Column Name Data Type Description

LIBRARY_NAME VARCHAR(10) Name of the library containing the database object.


Can contain the null value when CATEGORY is DBXREF SERVER.

OBJECT_NAME VARCHAR(128) Name of the database object.


Can contain the null value when CATEGORY is DBXREF SERVER.

OBJECT_TYPE VARCHAR(30) Type of database object.


Can contain the null value when CATEGORY is DBXREF SERVER.

SEVERITY VARCHAR(7) The severity of the reported item.

ERROR This row indicates an error that should be corrected.

INFO This row provides information about processing that was


performed.

WARNING This row indicates a problem that should be investigated, but


it does not indicate a serious problem.

366 IBM i: Performance and Query Optimization


Table 73. ANALYZE_CATALOG table function (continued)

Column Name Data Type Description

CATEGORY VARCHAR(20) The category of this catalog row.

CONSTRAINT An inconsistency was found with a *FILE object


constraint.

DBXREF SERVER An inconsistency was found with the database cross


reference server jobs.

RECLAIM The CATALOG_NAME for this row is known to be


inconsistent. Either RCLDBXREF *FIX or RCLSTG
SELECT(*DBXREF) is required. Use RCLDBXREF
*CHECK to determine the action that needs to be
taken.

DESCRIPTION VARCHAR(250) A text description of the inconsistency in the database catalog.

DETAIL VARCHAR(128) Additional detail about the inconsistency.


• When CATEGORY is CONSTRAINT, this is the name of the constraint.
• When CATEGORY is DBXREF SERVER, this can contain the number of
entries in the cross reference queue
Contains the null value if this row does not have additional detail
information.

CATALOG_LIBRARY VARCHAR(10) The name of the library containing the catalog.


Contains the null value if this row is not related to a specific catalog.

CATALOG_NAME VARCHAR(10) The catalog table that contains inconsistent information.


Contains the null value if this row is not related to a specific catalog.

Example
• Determine if there are any constraint inconsistencies for any database files on the system.

SELECT * FROM TABLE(QSYS2.ANALYZE_CATALOG(OPTION => 'DBXREF'));

• Determine if there are any constraint inconsistencies for database files in library APPLIB.

SELECT * FROM TABLE(QSYS2.ANALYZE_CATALOG(OPTION => 'DBXREF',


LIBRARY_NAME =>'APPLIB'));

• Examine how the database cross reference servers are running. If they are behind on processing, the
DESCRIPTION and DETAIL columns will indicate the number of entries in the queue that are waiting to
be processed.

SELECT * FROM TABLE(QSYS2.ANALYZE_CATALOG(OPTION => 'DBXREF SERVER'));

CANCEL_SQL procedure
The CANCEL_SQL procedure requests cancellation of an SQL statement for the specified job.
Authorization: None required if the caller’s user profile is the same as the job user identity of the
qualified job which is being canceled. Otherwise, the caller must have *JOBCTL special authority or be
authorized to the QIBM_DB_SQLADM function usage ID.

CANCEL_SQL ( job-name )

The schema is QSYS2.

job-name A character string containing the qualified job name to be canceled. It must be in upper case.

The CANCEL_SQL() procedure provides an alternative to end job immediate. It supports all application
and interactive SQL environments.
When an SQL cancel is requested, an asynchronous request is sent to the job identified by job-name.
If the job is processing an interruptible, long-running machine operation, analysis is done within the job

Database performance and query optimization 367


to determine whether it is safe to cancel the statement. When it is determined to be safe to cancel the
statement, an SQL0952 escape message is sent, causing the statement to terminate.
If it isn't safe to end the SQL statement, or if there is no active SQL statement, the request to cancel is
ignored. The caller of the cancel procedure will observe a successful return which only indicates that the
caller had the necessary authority to request a cancel and that the target job exists. The caller of the
CANCEL_SQL() procedure has no programmatic means of determining that the cancel request resulted in
a cancelled SQL statement.
If the cancel request occurs during the act of committing or rolling back a commitment-control
transaction, the request is ignored.
Errors: The procedure will fail with a SQL0443 if the target job is not found. The procedure will fail with
SQL0443 and SQL0552 if the caller does not have authority.
Commitment control: When the target application is running without commitment control (COMMIT
= *NONE), the canceled SQL statement will terminate without rolling back the partial results of the
statement. If the canceled statement is a query, the query ends. However, if the canceled statement
was a long-running INSERT, UPDATE, or DELETE SQL statement, the changes made prior to cancellation
remain intact.
If the target application is using transaction management, the SQL statement is running under a
transaction savepoint level. When a long running INSERT, UPDATE, or DELETE SQL statement is canceled,
the changes made prior to cancellation are rolled back.
In both cases, the application receives control back with an indication that the SQL statement failed. It is
up to the application to determine the next action.

Example
Safely cancel a job running an SQL statement.

CALL QSYS2.CANCEL_SQL('483456/QUSER/QZDASOINIT')

CHECK_SYSCST procedure
The CHECK_SYSCST procedure compares entries in the QSYS2.SYSCST table between two systems.
Authorization: See Note below.

CHECK_SYSCST ( remote-rdb-name , schema-name


, avoid-result-set

The schema is SYSTOOLS.

remote-rdb-name A character string containing the name of the remote database.


schema-name A character string containing the name of the schema to compare.
avoid-result-set An integer value that indicates whether a result set should be returned. The default
is 0.

1 No result set is returned.


0 Result set is returned.

This procedure will return a result set to the caller. If no result set is requested, the differences are logged
to the SESSION.SYSCSTDIFF table.
The result set that is returned or the table that is created contains the following columns:

368 IBM i: Performance and Query Optimization


Table 74. SYSCSTDIFF result set

Column Name System Column Name Data Type Description

SERVER_NAME SRVRNAME VARCHAR(18) Name of server where the request was run.

CONSTRAINT_SCHEMA CDNAME VARCHAR(128) Name of the schema containing the constraint.

CONSTRAINT_NAME RELNAME VARCHAR(128) Name of the constraint.

CONSTRAINT_TYPE TYPE VARCHAR(11) Type of constraint.

TABLE_SCHEMA TDBNAME VARCHAR(128) Name of schema containing the table.

TABLE_NAME TBNAME VARCHAR(128) Name of the table which the constraint is created over.

SYSTEM_TABLE_SCHEMA SYS_DNAME CHAR(10) System name of schema containing the table.

SYSTEM_TABLE_NAME SYS_TNAME CHAR(10) System name of the table which the constraint is created over.

CONSTRAINT_KEYS COLCOUNT SMALLINT Specifies the number of key columns if this is a UNIQUE,
PRIMARY KEY, or FOREIGN KEY constraint.

CONSTRAINT_STATE CST_STATE VARCHAR(11) Indicates whether the constraint is established or defined.

ENABLED ENABLED VARCHAR(3) Indicates whether the constraint is enabled or disabled.

CHECK_PENDING CHECK00001 VARCHAR(3) Indicates whether the constraint is in check pending state.

Note
This procedure is provided in the SYSTOOLS schema as an example of how to compare catalog tables
between systems using an SQL procedure. Similar to other Db2 for i provided tools within SYSTOOLS,
the SQL source can be extracted and used as a model for building similar procedures, or to create a
customized version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Find all the differences in constraint settings between the current system and LP01UT18 for the
CORPDB_EX schema:

CALL SYSTOOLS.CHECK_SYSCST('LP01UT18', 'CORPDB_EX')

Related reference
SYSTOOLS
SYSTOOLS is a set of Db2 for IBM i supplied examples and tools.

CHECK_SYSROUTINE procedure
The CHECK_SYSROUTINE procedure compares entries in the QSYS2.SYSROUTINES table between two
systems.
Authorization: See Note below.

CHECK_SYSROUTINE (

remote-rdb-name , schema-name )
, avoid-result-set

The schema is SYSTOOLS.

remote-rdb-name A character string containing the name of the remote database.


schema-name A character string containing the name of the schema to compare.

Database performance and query optimization 369


avoid-result-set An integer value that indicates whether a result set should be returned. The default
is 0.

1 No result set is returned.


0 Result set is returned.

This procedure will return a result set to the caller. If no result set is requested, the differences are logged
to the SESSION.SYSRTNDIFF table.
The result set that is returned or the table that is created contains the following columns:
Table 75. SYSRTNDIFF result set

Column Name System Column Name Data Type Description

SERVER_NAME SRVRNAME VARCHAR(18) Name of server where the request was run.

ROUTINE_CREATED RTNCREATE TIMESTAMP The timestamp when the routine was created.

ROUTINE_DEFINER DEFINER VARCHAR(128) Name of the user that defined the routine.

LAST_ALTERED ALTEREDTS TIMESTAMP Timestamp when routine was last altered.

SPECIFIC_SCHEMA SPECSCHEMA VARCHAR(128) Schema name of the routine instance.

SPECIFIC_NAME SPECNAME VARCHAR(128) Specific name of the routine instance.

ROUTINE_SCHEMA RTNSCHEMA VARCHAR(128) Name of the schema that contains the routine.

ROUTINE_NAME RTNNAME VARCHAR(128) Name of the routine.

ROUTINE_TYPE RTNTYPE VARCHAR(9) Type of the routine.

ROUTINE_BODY BODY VARCHAR(8) Type of the routine body.

EXTERNAL_NAME EXTNAME VARCHAR(279) External program name for routine.

IN_PARMS IN_PARMS SMALLINT Identifies the number of input parameters.

OUT_PARMS OUT_PARMS SMALLINT Identifies the number of output parameters.

INOUT_PARMS INOUT_PARM SMALLINT Identifies the number of input/output parameters.

SQL_DATA_ACCESS DATAACCESS VARCHAR(8) Identifies whether a routine contains SQL and whether it reads or
modifies data.

PARM_SIGNATURE SIGNATURE VARCHAR(2048) The signature of the routine.

Note
This procedure is provided in the SYSTOOLS schema as an example of how to compare catalog tables
between systems using an SQL procedure. Similar to other Db2 for i provided tools within SYSTOOLS,
the SQL source can be extracted and used as a model for building similar procedures, or to create a
customized version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Compare the current system to a remote system to find which routines differ, when they were created,
and who created them.

CALL SYSTOOLS.CHECK_SYSROUTINE('LP01UT18', 'CORPDB_EX')

Related reference
SYSTOOLS

370 IBM i: Performance and Query Optimization


SYSTOOLS is a set of Db2 for IBM i supplied examples and tools.

COMPARE_FILE table function


The COMPARE_FILE table function returns differences between the specified files, including SQL tables,
physical files, and source physical files.
A value of YES or QUICK must be specified for at least one of the compare-attributes or compare-data
parameters.
When comparing attributes, one row is returned for each attribute that is different between the files.
When comparing data, one row is returned for each row of data that is different between the files. The
relative record number (RRN) is returned to identify the row. Files with multiple members, including
partitioned tables and source physical files, where significant differences are found in the definition are
not eligible for data comparison. All the member names must match. A result row will be returned to
indicate that data comparison was not performed.
If a quick compare is requested, one row is returned if any difference is found. This compare option is
faster because a complete list of differences is not returned.
If no differences are found, no rows are returned.
Authorization: The caller must have:
• *EXECUTE authority on the library containing the file, and
• *OBJOPR and *READ authority to the file.
The caller must have *ALLOBJ or *AUDIT special authority to compare the object auditing attribute for the
files. If the caller does not have this authority, a difference in this value will not be reported.
To specify a parallel degree value other than NONE, the privileges held by the authorization ID of the
statement must include *JOBCTL special authority or have QIBM_DB_SQLADM function usage.

COMPARE_FILE ( library1 , file1


LIBRARY1 => FILE1 =>

, library2 , file2
LIBRARY2 => FILE2 =>

, rdb2
RDB2 =>

, compare-attributes
COMPARE_ATTRIBUTES =>

, compare-data
COMPARE_DATA =>

)
, parallel-degree
PARALLEL_DEGREE =>

The schema is QSYS2.

library1 A character or graphic string expression that identifies the library that contains file1. It
must exist on the current server and cannot be QTEMP.

Database performance and query optimization 371


file1 A character or graphic string expression that identifies the first file for the compare. This
must be the system name of the file.
library2 A character or graphic string expression that identifies the library that contains file2. It
must exist on the server implicitly or explicitly identified by rdb2 and cannot be QTEMP.
If library2 is omitted, library1 is used.
file2 A character or graphic string expression that identifies the second file for the compare.
This must be the system name of the file. The two files cannot be the same file object.
If file2 is omitted, file1 is used.
rdb2 A character or graphic string expression that identifies the relational database where
library2 exists. If this parameter is omitted, library2 must exist on the current server.
compare- A character or graphic string expression that indicates whether attributes are compared
attributes for the file.

NO The attributes are not compared for the file.


QUICK The attributes are compared for the file until the first difference is found. Only
a single row is returned if any differences are detected. This option is faster
because a complete list of differences is not returned.
YES All the attributes are compared for the file. A row is returned for each difference
found. This is the default.

compare- A character or graphic string expression that indicates whether the data is compared for
data the file, including the relative record number (RRN) of each row.

NO The data is not compared for the file.


QUICK The data is compared for the file until the first difference is found. Only a single
row is returned if any differences are detected. This option is faster because a
complete list of differences is not returned.
YES All the data is compared for the file. A row is returned for each difference found.
This is the default.

parallel- A character or graphic string that specifies the maximum degree of parallelism to use
degree when comparing the file.
If the Db2 Symmetric Multiprocessing (SMP) feature is not installed, a warning is issued if
the value is not NONE and the compare will not use parallelism.

2-256 The maximum degree of parallelism to be used. Using parallelism can cause the
compare to complete sooner, but it will have an impact on system resources.
NONE No parallelism will be used. This is the default.

The result of the function is a table containing rows with the format shown in the following table. All
columns are nullable.
Table 76. COMPARE_FILE table function

Column Name Data Type Description

ATTRIBUTE_NAME VARGRAPHIC(512) The name of file attribute or the relative record number (RRN) that is
not identical.
CCSID 1200

FILE1 VARGRAPHIC(2048) The value for file1.

CCSID 1200

FILE2 VARGRAPHIC(2048) The value for file2.

CCSID 1200

372 IBM i: Performance and Query Optimization


Examples
• Compare the attributes and data for file T1 between the TEST library and the PROD library.

SELECT * FROM TABLE(QSYS2.COMPARE_FILE(


LIBRARY1=>'TEST', FILE1=>'T1',
LIBRARY2=>'PROD', FILE2=>'T1'));

• Compare the data for file T1 between the TEST library and the PROD library. As soon as any difference is
detected, stop the compare.

SELECT * FROM TABLE(QSYS2.COMPARE_FILE(


LIBRARY1=>'TEST', FILE1=>'T1',
LIBRARY2=>'PROD', FILE2=>'T1',
COMPARE_ATTRIBUTES=>'NO',
COMPARE_DATA=>'QUICK'));

DUMP_SQL_CURSORS procedure
The DUMP_SQL_CURSORS procedure lists the open cursors for a job.
Authorization: None required if the caller's user profile is same as the job user identity of the qualified job
for which the open cursors are being listed. Otherwise, the caller must have *JOBCTL special authority or
be authorized to the QIBM_DB_SQLADM or QIBM_DB_SYSMON function usage ID.
To place the results in library-name.file-name, the caller must have:
• *EXECUTE authority to the library, and
• *OBJOPR and *ADD authorities to the file.
If the file does not exist, the caller must have *ADD authority to the library.

DUMP_SQL_CURSORS ( job-name ,
JOB_NAME =>

library-name ,
LIBRARY_NAME => FILE_NAME =>

file-name , output-option )
OUTPUT_OPTION =>

The schema is QSYS2.

job-name A character string containing a qualified job name or a value of '*' to indicate the current
job
library-name A character string containing a system library name for the procedure output. An empty
string is allowed.
file-name A character string containing a system file name for the procedure output. An empty
string is allowed.
output-option An integer value that indicates how to return the output.

1 Ignore library-name and file-name parameters and return a result set.


2 Ignore library-name and file-name parameters and place the results in table QTEMP/
SQL_CURSORS.
3 Place the results in file file-name in library library-name. If the file doesn't exist, it
will be created. If the file already exists, the results will be appended to the existing
file.

Database performance and query optimization 373


4 Place the results in file file-name in library library-name. If the file doesn't exist, it
will not be created.

The result set that is returned or the file that is created contains the following columns:
Table 77. DUMP_SQL_CURSORS result table

Column Name System Column Name Data Type Description

SQL_IDENTITY SQL_I00001 INTEGER Unique identifier for the row.

DUMPTIME DUMPTIME TIMESTAMP Timestamp when row was inserted.

DUMP_BY_USER DUMPUSER VARCHAR(18) User ID used to insert row.

CURSOR_NAME CSRNAME VARCHAR(128) Name of the cursor.

PSEUDO_CLOSED PSEUDO VARCHAR(3) Pseudo close state of the cursor.

YES Cursor is currently pseudo closed.

NO Cursor is currently opened.

STATEMENT_NAME STMTNAME VARCHAR(128) Name of the statement corresponding to the cursor

OBJECT_NAME OBJNAME CHAR(10) Object containing the current SQL statement. Blank if current
SQL statement is not in a program, service program, or package.

OBJECT_LIBRARY OBJLIB CHAR(10) Library for object containing the current SQL statement. Blank if
current SQL statement is not in a program, service program, or
package.

OBJECT_TYPE OBJTYPE CHAR(10) Type of object containing the current SQL statement. Blank if
current SQL statement is not in a program, service program, or
package.

JOBNAME JOBNAME CHAR(28) System job name for the cursor. Contains * if current job was
specified for job-name argument.

Example
Populate QGPL/SQLCSR1 file with open SQL cursors for the current job.

CALL QSYS2.DUMP_SQL_CURSORS('*', 'QGPL', 'SQLCSR1', 3);

END_IDLE_SQE_THREADS procedure
The END_IDLE_SQE_THREADS procedure will end any idle SQE threads for the current job.
Authorization: None required.

END_IDLE_SQE_THREADS ( )

The schema is QSYS2.


When the SQE database engine runs a query using Symmetric Multiprocessing (SMP) or a query that
contains a fenced UDF or UDTF, system threads are started. These threads may be left active for a period
of time so that they are eligible to be re-used. This can cause problems with an application when a
non-threadsafe command is executed after the query is run. When this happens the application receives
an error message, CPF180B "Function XXXX is not allowed in a job which has multiple threads." Running
the END_IDLE_SQE_THREADS procedure will end all SQE threads for the job that are not actively being
used, so this error can be avoided.

Example
• End the idle SQE threads.

CALL QSYS2.END_IDLE_SQE_THREADS();

374 IBM i: Performance and Query Optimization


EXTRACT_STATEMENTS procedure
The EXTRACT_STATEMENTS procedure returns details from an SQL plan cache snapshot, an SQL
performance monitor, or an SQL plan cache event monitor in the form of an SQL table or a result set.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the database monitor file, and
• *OBJOPR, *READ, and *UPDATE authorities to the database monitor file.
If output-schema and output-table are used to create a table, the caller must have:
• *OBJOPR, *READ, *EXECUTE, and *ADD authorities to output-schema, and
• *USE to the Create Physical File (CRTPF) command
If output-schema and output-table are used to append to a table, the caller must have:
• *USE authority to output-schema, and
• *OBJOPR and *ADD authorities to output-table

EXTRACT_STATEMENTS ( monitor-schema ,
MONITOR_SCHEMA =>

monitor-name
MONITOR_NAME =>

, additional-select-columns
ADDITIONAL_SELECT_COLUMNS =>

, additional-predicates
ADDITIONAL_PREDICATES =>

, order-by
ORDER_BY =>

, output-schema
OUTPUT_SCHEMA =>

)
, output-table
OUTPUT_TABLE =>

The schema is QSYS2.

monitor- A character or graphic string expression that identifies the name of the library
schema containing monitor-name.
monitor-name A character or graphic string expression that identifies the name of an existing
database monitor file.
additional- A character or graphic string of up to 5000 characters containing additional columns
select-columns or expressions to be appended to the generated SELECT clause. A value of *AUDIT will
cause the procedure to return the merged statement and columns that are normally
interesting for auditing.

Database performance and query optimization 375


If additional-select-columns is not specified or is the null value, no additions are made
to the generated SELECT clause.

additional- A character or graphic string of up to 5000 characters containing additional predicates


predicates to be appended to the generated WHERE clause.
If additional-predicates is not specified or is the null value, no additions are made to
the generated WHERE clause.

order-by A character or graphic string of up to 5000 characters containing additional options to


be appended to the end of the generated query. This can include the ORDER BY clause
or other clauses such as FETCH FIRST n ROWS.
If order-by is not specified or is the null value, no additions are made to the end of the
query.

output-schema The schema name for the output table.


If output-schema is not specified, the null value is used.

output-table The table name to contain the output. If the table identified by output-schema and
output-table does not exist, it will be created. If the table exists, the result of this
calling this procedure will be appended to the table. For an existing table, the number
of selected columns must match the selected columns when the table was generated.
If output-name is not specified, the null value is used.

If output-schema or output-table is the null value, a result set containing the extracted statement
information is returned.

Examples
• Extract the 100 most recent statements from monitor APRIL1014:

CALL QSYS2.DUMP_PLAN_CACHE('SNAPSHOTS', 'APRIL2014');

CALL QSYS2.EXTRACT_STATEMENTS('SNAPSHOTS', 'APRIL2014', '*AUDIT',


'AND QQC21 NOT IN
(''CH'', ''CL'', ''CN'', ''DE'', ''DI'', ''DM'', ''HC'', ''HH'', ''JR'', ''FE'',
''PD'', ''PR'', ''PD'')',
' ORDER BY QQSTIM DESC FETCH FIRST 100 ROWS ONLY ');

• Extract all the queries where the query took longer than one second:

CALL QSYS2.DUMP_PLAN_CACHE('SNAPSHOTS', 'APRIL2014');

CALL QSYS2.EXTRACT_STATEMENTS('SNAPSHOTS', 'APRIL2014',


ADDITIONAL_SELECT_COLUMNS => 'DECIMAL(QQI6)/1000000.0 as Total_time,
QVC102 as Current_User_Profile ',
ADDITIONAL_PREDICATES => ' AND QQI6 > 1000000 ',
ORDER_BY => ' ORDER BY QQI6 DESC ');

FIND_AND_CANCEL_QSQSRVR_SQL procedure
The FIND_AND_CANCEL_QSQSRVR_SQL procedure finds a set of jobs with SQL activity and safely cancels
them.
The FIND_AND_CANCEL_QSQSRVR_SQL procedure uses the FIND_QSQSRVR_JOBS and CANCEL_SQL
procedures to determine the set of jobs that have SQL activity for the provided job-name. Each of these
jobs is made a target of an SQL cancel request.
Authorization: The caller must have:
• QSYS2/FIND_QSQSRVR_JOBS() authorizations, and
• QSYS2/CANCEL_SQL() authorizations

376 IBM i: Performance and Query Optimization


FIND_AND_CANCEL_QSQSRVR_SQL ( job-name )

The schema is QSYS2.

job-name A character string containing a qualified job name.

Example
Cancel all the QSQSRVR jobs used by a specific job.

CALL QSYS2.FIND_AND_CANCEL_QSQSRVR_SQL('564321/APPUSER/APPJOBNAME')

FIND_QSQSRVR_JOBS procedure
The FIND_QSQSRVR_JOBS procedure returns information about a QSQSRVR job.
Authorization: The caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM or QIBM_DB_SYSMON function usage ID.

FIND_QSQSRVR_JOBS ( job-name )

The schema is QSYS2.

job-name A character string containing a qualified job name.

If the specified job is active and is set up to use SQL server mode, the procedure determines which
QSQSRVR jobs are being used by the application in the form of active SQL server mode connections.
The procedure collects and returns work management, performance, and SQL information. It returns two
SQL result sets, one containing summary information and one containing detailed SQL server mode job
information.
The results of the procedure call are saved in two temporary tables, QTEMP.QSQSRVR_SUMMARY and
QTEMP.QSQSRVR_DETAIL. When called from within IBM i Navigator Run SQL Scripts, two results sets are
displayed. When called from other interfaces, you need to query the temporary tables to see the data.
The result sets that are returned or the tables that are created contain the following columns:
Table 78. FIND_QSQSRVR_JOBS result set 1

Column Name System Column Name Data Type Description

SQL_IDENTITY SQL_I00001 INTEGER Unique identifier for this row.

NUMBER_OF_ACTIVE_JOBS NUMJOBS INTEGER Number of QSQSRVR jobs active for this job.

SERVER_MODE_JOB SRVRJOB CHAR(28) The fully qualified QSQSRVR job name for an active SQL Server
Mode connection established by job-name.

SERVER_MODE_CONNECTING_JOB CONNJOB CHAR(28) The fully qualified job name of the application job. This value
matches what was input for job_name.

TOTAL_PROCESSING_TIME TOTALCPU BIGINT The total amount of CPU time (in milliseconds) that has been
used by all server jobs.

TEMP_MEG_STORAGE TEMPMSTG INTEGER The total amount of auxiliary storage (in megabytes) that is
currently allocated to all server jobs.

PAGE_FAULTS FAULTS BIGINT The total number of times an active program referenced an
address that was not in main storage for all server jobs.

IO_REQUESTS IOREQS BIGINT The total number of auxiliary I/O requests performed by the job
across all routing steps for all server jobs. This includes both
database and non-database paging.

Database performance and query optimization 377


Table 79. FIND_QSQSRVR_JOBS result set 2

System Column
Column Name Name Data Type Description

SQL_IDENTITY SQL_I00001 INTEGER Unique identifier for this row.

JOB_NAME JOBNAME CHAR(10) Job name.

USER_NAME USERNAME CHAR(10) User ID for the job.

JOB_NUMBER JOBNUM CHAR(6) Job number.

JOB_INTERNAL_IDENTIFIER JOBID CHAR(16) Internal identifer assigned to job.

CURRENT_USERNAME CURRUSER CHAR(10) The user profile that the thread is currently running under.

SUBSYSTEM_DESCRIPTION_NAME SBSNAME CHAR(10) Name of subsystem where job is running.

RUN_PRIORITY PRIORITY INTEGER The highest run priority allowed for any thread within this job.

SYSTEM_POOL_IDENTIFIER POOLID INTEGER The identifier of the system-related pool from which the job's main
storage is allocated.

TOTAL_PROCESSING_TIME TOTALCPU BIGINT The amount of CPU time (in milliseconds) that has been currently
used by this job.

PAGE_FAULTS FAULTS BIGINT The number of times an active program referenced an address
that was not in main storage during the current routing step of the
specified job.

IO_REQUESTS IOREQS BIGINT The number of auxiliary I/O requests performed by the job across
all routing steps. This includes both database and non-database
paging.

MEMORY_POOL_NAME POOLNAME CHAR(10) The name of the memory pool in which the job started running.

TEMP_MEG_STORAGE TEMPMSTG INTEGER The amount of auxiliary storage (in megabytes) that is currently
allocated to this job.

TIME_SLICE TSLICE INTEGER The maximum amount of processor time (in milliseconds) given to
each thread in this job before other threads in this job and in other
jobs are given the opportunity to run.

DEFAULT_WAIT DFTWAIT INTEGER The default maximum time (in seconds) that a thread in the job
waits for a system instruction to acquire a resource.

SQL_APPLICATION_LIBRARY SQLLIB CHAR(10) The library name for the SQL statement object.

SQL_APPLICATION_PROGRAM SQLPGM CHAR(10) The program, service program, or package name of the object
which contains the last SQL statement executed in the job.

SQL_APPLICATION_TYPE APPTYPE CHAR(10) The object type.

SERVER_MODE_CONNECTING_JOB CONNJOB CHAR(28) The qualified job name of the job which established the SQL Server
Mode connection.

SERVER_MODE_CONNECTED_THREAD CONNTHD CHAR(10) The thread identifier of the last thread to use this connection.

STATUS_OF_CURRENT_SQL_STMT STMTSTAT CHAR(10) Status of the SQL statement. Values are ACTIVE or COMPLETED.

SQL_STATEMENT SQLSTMT VARCHAR(1000) First 1000 characters of the SQL statement.

GENERATE_SQL procedure
The GENERATE_SQL procedure generates the SQL data definition language statements required to
recreate a database object. The results are returned in the specified database source file member, source
stream file, or as a result set.
The database source file member or integrated file system (IFS) stream file will contain the generated
SQL statements. If the output source file is QTEMP/Q_GENSQL with a member name of Q_GENSQL, the
source file is returned as a result set as well.
Authorization:
When writing to a database source physical file the caller must have:
• *EXECUTE to the library containing the source physical file
• To add a member:
– *OBJOPR and *ADD to the source physical file

378 IBM i: Performance and Query Optimization


• To replace a member:
– *OBJOPR, *DELETE, *ADD, and either *OBJMGT or *OBJALTER to the source physical file
When writing to an IFS stream file:
• Execute (*X) data authority to each directory preceding the stream file being written and
• When the stream file exists:
– Write (*W) data authority to the stream file
• When the stream file does not exist:
– Write and Execute (*WX) authority to the parent directory of the stream file
To generate source for an object type, the following authorities are needed:
• TABLE, VIEW, CONSTRAINT, or TRIGGER
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *FILE object
• INDEX
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *FILE object, and
– *OBJOPR to the base *FILE object
• MASK or PERMISSION
– *EXECUTE and *OBJOPR to the library, and at least one of the following:
- *OBJOPR to the *FILE object
- QIBM_DB_SECADM function usage
• ALIAS
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *FILE object
• FUNCTION or PROCEDURE
– *OBJOPR to the library
• TYPE
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *SQLUDT object
• SCHEMA
– *OBJOPR and either *READ or *EXECUTE to the *LIB object
• SEQUENCE
– *EXECUTE and *OBJOPR to the library, and
– *USE to the *DTAARA object
• VARIABLE
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *SRVPGM object
• XSR
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *SQLXSR object

Database performance and query optimization 379


GENERATE_SQL ( database-object-name ,
DATABASE_OBJECT_NAME =>

database-object-library-name ,
DATABASE_OBJECT_LIBRARY_NAME =>

database-object-type
DATABASE_OBJECT_TYPE =>

, database-source-file-name
DATABASE_SOURCE_FILE_NAME =>

, database-source-file-library-name
DATABASE_SOURCE_FILE_LIBRARY_NAME =>

, database-source-file-member
DATABASE_SOURCE_FILE_MEMBER =>

, severity-level
SEVERITY_LEVEL =>

, replace-option
REPLACE_OPTION =>

, statement-formatting-option
STATEMENT_FORMATTING_OPTION =>

, date-format
DATE_FORMAT =>

, date-separator
DATE_SEPARATOR =>

, time-format
TIME_FORMAT =>

, time-separator
TIME_SEPARATOR =>

, naming-option
NAMING_OPTION =>

, decimal-point
DECIMAL_POINT =>

, standards-option
STANDARDS_OPTION =>

, drop-option
DROP_OPTION =>

, message-level
MESSAGE_LEVEL =>

, comment-option
COMMENT_OPTION =>

, label-option
LABEL_OPTION =>

, header-option
HEADER_OPTION =>

, trigger-option
TRIGGER_OPTION =>

, constraint-option
CONSTRAINT_OPTION =>

, system-name-option
SYSTEM_NAME_OPTION =>

, privileges-option
PRIVILEGES_OPTION =>

, ccsid-option
CCSID_OPTION =>

, create-or-replace-option
CREATE_OR_REPLACE_OPTION =>

, obfuscate-option
OBFUSCATE_OPTION =>

, activate-access-control-option
ACTIVATE_ROW_AND_COLUMN_ACCESS_CONTROL_OPTION =>

, mask-and-permission-option
MASK_AND_PERMISSION_OPTION =>

, qualified-name-option
QUALIFIED_NAME_OPTION =>

, additional-index-option
ADDITIONAL_INDEX_OPTION =>

, index-instead-of-view-option
INDEX_INSTEAD_OF_VIEW_OPTION =>

, temporal-option
TEMPORAL_OPTION =>

, source-stream-file
SOURCE_STREAM_FILE =>

, source-stream-file-end-of-line
SOURCE_STREAM_FILE_END_OF_LINE =>

)
, source-stream-file-ccsid
SOURCE_STREAM_FILE_CCSID =>

The schema is QSYS2.

database- A character or graphic string expression that identifies the name of the database object
object-name for which DDL will be generated. Either the SQL name or the system name may be

380 IBM i: Performance and Query Optimization


specified. The name is case sensitive. Delimiters must not be specified. For example,
a file with a name of "abc" must be specified as abc. A file with a name of ABC must
be specified in upper case. If the object type is a FUNCTION or PROCEDURE, this name
must be the specific name of the function or procedure. If TABLE or VIEW is specified
for the object type, the object name may identify an alias. In this case, the object that
the alias points to will be generated. A CREATE ALIAS statement will be generated only
if ALIAS is specified for the object type.
A '%' wildcard character can be used to select multiple objects of the same type. For
example, a name of 'TSTV%' will process all objects of database-object-type that start
with the characters 'TSTV'
database- A character or graphic string expression that identifies the name of the library containing
object-library- the object for which DDL will be generated. Either the SQL name or the system name
name may be specified. The name is case sensitive. Delimiters must not be specified. This
name is ignored if the specified object type is SCHEMA. A '%' wildcard character can be
used to select multiple libraries.
database- A character or graphic string expression that identifies the type of the database object
object-type or object attribute for which DDL is generated. You can use these special values for the
object type:

ALIAS The object is an SQL alias.


CONSTRAINT The object attribute is a constraint.
FUNCTION The object is an SQL function.
INDEX The object is an SQL index.
MASK The object is an SQL column mask.
PERMISSION The object is an SQL row permission.
PROCEDURE The object is an SQL procedure.
SCHEMA The object is an SQL schema.
SEQUENCE The object is an SQL sequence.
TABLE The object is an SQL table or physical file.
TRIGGER The object attribute is a trigger.
TYPE The object is an SQL type.
VARIABLE The object is an SQL global variable.
VIEW The object is an SQL view or logical file.
XSR The object is an XML schema repository object.

database- A character or graphic string expression that identifies the name of the source file that
source-file- contains the SQL statements generated by the procedure. The name must be a valid
name system name. The name is case sensitive. If delimiters are required for the name to be
valid, they must be specified. For example, a file with a name of "abc" must be specified
with the surrounding quotes. A file with a name of ABC must be specified in upper case.
The record length of the specified source file must be greater than or equal to 92.
Can contain the following special value:

*STMF The output is to be written to source-stream-file.

If database-source-file-name is not specified, Q_GENSQL will be used.


database- A character or graphic string expression that identifies the name of the library containing
source-file- the source file that contains the SQL statements generated by the procedure. The name
library-name must be a valid system name. The name is case sensitive. If delimiters are required for

Database performance and query optimization 381


the name to be valid, they must be specified. You can use these special values for the
library name:

*CURLIB The job's current library


*LIBL The library list

If database-source-file-library-name is not specified, QTEMP will be used.


database- A character or graphic string expression that identifies the name of the source file
source-file- member that contains the SQL statements generated by the procedure. The name must
member be a valid system name. The name is case sensitive. If delimiters are required for the
name to be valid, they must be specified. You can use these special values for the
member name:

*FIRST The first database physical file member found.


*LAST The last database physical file member found.

If values are provided for database-source-file-library-name, database-source-file-


name, and database-source-file-member the object must exist.
If database-source-file-member is not specified, Q_GENSQL will be used.

severity-level The severity level at which the operation fails. If errors occur that have a severity level
greater than this value, the operation ends. The valid values are in the range 0 through
39 inclusive. Any severity 40 error will cause the procedure to fail.
If severity-level is not specified, 39 will be used.
replace- The replace option for the database source file member or source stream file. The valid
option values are:

0 The resulting SQL statements are appended to the end of the database source file
member or source stream file.
1 The database source file member or source stream file is cleared prior to adding the
resulting SQL statements. If this option is chosen, the clear might happen even if an
error is returned from the procedure.

If replace-option is not specified, 1 will be used.


statement- The formatting option used in the generated SQL statements. The valid values are:
formatting-
option 0 No additional formatting characters are added to the generated SQL statements.
1 Additional end-of-line characters and tab characters are added to the generated
SQL statements.

If statement-formatting-option is not specified, 1 will be used.


date-format The date format used for date constants in a generated SQL CREATE TABLE statement.
The date format may not apply to date constants that are in ISO, EUR, USA, or JIS
format in a CREATE VIEW, CREATE TRIGGER, CREATE FUNCTION, CREATE PROCEDURE,
CREATE MASK, or CREATE PERMISSION.
If date-format is not specified, ISO will be used.
date- The date separator used for date constants in a generated SQL CREATE TABLE
separator statement. The date separator may not apply to date constants that are in ISO, EUR,
USA, or JIS format in a CREATE VIEW, CREATE TRIGGER, CREATE FUNCTION, CREATE
PROCEDURE, CREATE MASK, or CREATE PERMISSION statement.
If date-separator is not specified, - will be used.
time-format The format used for time constants in a generated SQL CREATE TABLE statement. The
time format may not apply to time constants that are in ISO, EUR, USA, or JIS format in

382 IBM i: Performance and Query Optimization


a CREATE VIEW, CREATE TRIGGER, CREATE FUNCTION, CREATE PROCEDURE, CREATE
MASK, or CREATE PERMISSION statement.
If time-format is not specified, ISO will be used.
time- The time separator used for time constants in a generated SQL CREATE TABLE
separator statement. The time separator may not apply to time constants that are in ISO, EUR,
USA, or JIS format in a CREATE VIEW, CREATE TRIGGER, CREATE FUNCTION, CREATE
PROCEDURE, CREATE MASK, or CREATE PERMISSION statement.
If time-separator is not specified, . will be used.
naming- The naming convention used for qualified names in the generated SQL statements. The
option valid values are:

SQL schema.table syntax


SYS library/file syntax

If naming-option is not specified, SQL will be used.


decimal-point The decimal point used for numeric constants. The valid values are:

. Period separator
, Comma separator

If decimal-point is not specified, . will be used.


standards- The standards option specifies whether the generated SQL statements should contain
option Db2 for i extensions or whether the statements should conform to the Db2 family SQL or
to the ANS and ISO SQL standards. The valid values are:

0 Db2 for i extensions may be generated in SQL statements.


1 The generated SQL statements must conform to SQL statements common to the
Db2 family.
2 The generated SQL statements must conform to the ANSI and ISO SQL standards.

If standards-option is not specified, 0 will be used.


drop-option The drop option specifies whether DROP (or ALTER) SQL statements should be
generated prior to the CREATE statement to drop the specified object. The valid values
are:

0 DROP statements should not be generated.


1 DROP statements should be generated.

If drop-option is not specified, 0 will be used.


message-level The severity level at which the messages are generated. If errors occur that have a
severity level greater than this value, a message is generated in the output. The valid
values are in the range 0 through 39 inclusive. The message level must be less than or
equal to the severity level.
If message-level is not specified, 0 will be used.
comment- The comment option specifies whether COMMENT SQL statements should be generated
option if a comment exists on the specified database object. If comments are not supported by
the specified database object, the comment option is ignored. The valid values are:

0 COMMENT SQL statements should not be generated.


1 COMMENT SQL statements should be generated. If the specified database object
type is a table or view, COMMENT SQL statements will also be generated for
columns of the table or view.

Database performance and query optimization 383


2 COMMENT SQL statements should be generated. If the specified database object
has no comment and its type is INDEX, SEQUENCE, TABLE, TYPE, VARIABLE, VIEW,
or XSR, the system object text will be used for the comment.
If the specified database object type is a table or view, COMMENT SQL statements
will also be generated for columns of the table or view.

If comment-option is not specified, 1 will be used.


label-option The label option specifies whether LABEL SQL statements should be generated if a label
exists on the specified database object. If labels are not supported by the specified
database object, the label option is ignored. The valid values are:

0 LABEL SQL statements should not be generated.


1 LABEL SQL statements should be generated. If the specified database object type
is a table or view, LABEL SQL statements will also be generated for columns of the
table or view.

If label-option is not specified, 1 will be used.


header-option The header option specifies whether a header should be generated prior to the CREATE
statement. The header consists of comments that describe the version, date and time,
the relational database, and some of the options used to generate the SQL statements.
The valid values are:

0 A header should not be generated.


1 A header should be generated.

If header-option is not specified, 1 will be used.


trigger-option The trigger option specifies whether triggers should be generated when the object type
is a TABLE or VIEW. The valid values are:

0 Triggers should not be generated.


1 Triggers should be generated.

If trigger-option is not specified, 1 will be used.


constraint- The constraint option specifies whether constraints should be generated when the
option object type is a TABLE. The valid values are:

0 Constraints should not be generated.


1 Constraints should be generated.
2 Constraints should be generated as part of the CREATE TABLE statement.

If constraint-option is not specified, 1 will be used.


system-name- The system name option specifies whether a FOR SYSTEM NAME clause should be
option generated for the system name when it is different from the SQL name and the object
type is an INDEX, TABLE, VIEW, SEQUENCE, or VARIABLE. The valid values are:

0 A FOR SYSTEM NAME clause should not be generated.


1 A FOR SYSTEM NAME clause should be generated.

If system-name-option is not specified, 1 will be used.


privileges- The privileges option specifies whether GRANT SQL statements should be generated on
option the specified database object. If privileges are not supported by the specified database
object, the privileges option is ignored. The valid values are:

384 IBM i: Performance and Query Optimization


0 GRANT SQL statements should not be generated.
1 GRANT SQL statements should be generated.

If privileges-option is not specified, 1 will be used.


ccsid-option The CCSID option specifies whether the CCSID attribute should be generated for column
definitions when the object type is a TABLE. The valid values are:

0 CCSID attribute should not be generated.


1 CCSID attribute should be generated.

If ccsid-option is not specified, 1 will be used.


create-or- The create or replace option specifies whether CREATE OR REPLACE should be
replace- generated for the specified database object on the CREATE statement. This option is
option ignored if the specified database object does not support CREATE OR REPLACE. The
valid values are:

0 CREATE OR REPLACE should not be generated.


1 CREATE OR REPLACE should be generated.

If create-or-replace-option is not specified, 0 will be used.


obfuscate- The obfuscate option specifies whether an obfuscated SQL statement should be
option returned for SQL functions, SQL procedures, or SQL triggers that were not created using
obfuscated statements. This option is ignored if the standards option is not ‘0’. This
option is also ignored if the object is not an SQL function, procedure, or trigger. This
option is ignored if the object is already obfuscated. Setting Obfuscate option = 0 cannot
be used as a means of obtaining the unobfuscated SQL statement for an obfuscated
object. The valid values are:

0 An obfuscated statement should not be generated.


1 An obfuscated statement should be generated for SQL functions, SQL procedures, or
SQL triggers.

If obfuscate-option is not specified, 0 will be used.


activate- The activate row and column access control option specifies whether an ALTER TABLE to
access- activate row and column access control should be generated when the object type is a
control-option TABLE. This option is ignored if the standards option is not '0' or '1'. The valid values are:

0 Activate row and column access control should not be generated.


1 Activate row and column access control should be generated.

If activate-access-control-option is not specified, 1 will be used.


mask-and- The mask and permission option specifies whether row permissions and column masks
permission- should be generated when the object type is a TABLE. This option is ignored if the
option standards option is not '0' or '1'. The valid values are:

0 Permissions and masks should not be generated.


1 Permissions and masks should be generated.

If mask-and-permission-option is not specified, 1 will be used.


qualified- The qualified name option specifies whether qualified or unqualified names should be
name-option generated for the specified database object. The valid values are:

Database performance and query optimization 385


0 Qualified object names should be generated. Unqualified names within the body of
SQL routines will remain unqualified.
1 Unqualified object names should be generated when a library is found which
matches the database object library name. Any SQL object or column reference
that is RDB qualified will be generated in its fully qualified form. For example, rdb-
name.schema-name.table-name and rdb-name.schema-name.table-name.column-
name references will retain their full qualification.

If qualified-name-option is not specified, 0 will be used.


additional- The additional index option specifies whether additional CREATE INDEX statements will
index-option be generated for DDS-created keyed physical or logical files. The valid values are:

0 Additional CREATE INDEX statements will not be generated.


1 An additional CREATE INDEX statement will be generated that matches the index for
a DDS-created keyed physical file. If the physical file has a PRIMARY KEY constraint,
a CREATE INDEX statement is not generated.
An additional CREATE INDEX statement will be generated that matches the index for
a DDS-created keyed logical file. If a value of ‘1’ is specified for the index instead
of view option, an additional CREATE INDEX statement is not generated. Additional
CREATE INDEX statements will also be generated that match the join indexes of a
DDS-created join logical file.

If additional-index-option is not specified, 0 will be used.


index- The index instead of view option specifies whether a CREATE INDEX or CREATE VIEW
instead-of- statement will be generated for a DDS-created keyed logical file. The valid values are:
view-option
0 A CREATE VIEW statement will be generated.
1 A CREATE INDEX statement will be generated that matches the index for a DDS-
created keyed logical file.

If index-instead-of-view-option is not specified, 0 will be used.


temporal- The temporal option specifies whether a CREATE TABLE and an ALTER TABLE statement
option will be generated when the object type is a TABLE and the table is defined as a temporal
table. This option is ignored if the object is not a temporal table or if the standards
option is not ‘0’ or '1'. The valid values are:

0 A CREATE TABLE statement will be generated.


1 A CREATE TABLE statement will be generated and an ALTER TABLE statement will
be generated to add versioning.
2 Only an ALTER TABLE statement will be generated to add versioning.

If temporal-option is not specified, 0 will be used.


source- A character or graphic string expression that identifies the source stream file that
stream-file contains the SQL statements generated by the procedure. This parameter is ignored
unless database-source-file-name has a value of *STMF.
If the file does not exist, it will be created using the CCSID specified by source-stream-
file-ccsid. As lines are written to the file, source-stream-file-end-of-line determines the
end of line sequence, if any, to be appended to each line.
When source-stream-file is used, values provided for database-source-file-library-name
and database-source-file-member are ignored.
Writing to the QSYS.LIB file system is not supported.

386 IBM i: Performance and Query Optimization


source- A character or graphic string expression that defines the end of line character(s) which
stream-file- will be appended to the end of each line when writing to source-stream-file. The carriage
end-of-line return character is always X’0D’. Based on the CCSID of the source stream file, the line
feed character is X’25’ for an EBCDIC CCSID and X’0A’ for ASCII and UTF-8 CCSIDs. The
valid values are:

CR A carriage return is appended.


CRLF A carriage return and line feed are appended.
LF A line feed is appended.
LFCR A line feed and carriage return are appended.

If source-stream-file-end-of-line is not specified, CRLF will be used.


This parameter is ignored when writing to a source file.

source- An integer value that defines the CCSID to use if a new source stream file is created.
stream-file- If source-stream-file is specified and the source stream file does not exist, it will be
ccsid created with this CCSID value. A value of 0 indicates that the default job CCSID is to be
used. A CCSID of 65535 cannot be specified.
If source-stream-file-ccsid is not specified, 0 will be used.
This parameter is ignored when writing to a source file.

Examples
• Generate DDL for all tables in a schema and return the source as a result set.

CALL QSYS2.GENERATE_SQL('%', 'SAMPLE_CORPDB', 'TABLE', REPLACE_OPTION => '0');

• Generate DDL for all indexes starting with ‘X’ within the SAMPLE_CORPDB schema, place the output in a
file named DDLSOURCE/GENFILE member INDEXSRC.

CALL QSYS2.GENERATE_SQL('X%', 'SAMPLE_CORPDB', 'INDEX',


'GENFILE', 'DDLSOURCE', 'INDEXSRC',
REPLACE_OPTION => '0');

• Generate DDL for a single table and include the constraints within a CREATE OR REPLACE TABLE
statement.

CALL QSYS2.GENERATE_SQL('EMPLOYEE', 'SAMPLE_CORPDB', 'TABLE',


'GENFILE', 'DDLSOURCE', 'MASTERSRC',
CREATE_OR_REPLACE_OPTION => '1',
CONSTRAINT_OPTION => '2');

• Generate DDL for MYLIB.MYTABLE, placing the output in source stream file /usr/mytable_ddl.

CALL QSYS2.GENERATE_SQL(DATABASE_OBJECT_NAME => 'MYTABLE',


DATABASE_OBJECT_LIBRARY_NAME => 'MYLIB',
DATABASE_OBJECT_TYPE => 'TABLE',
DATABASE_SOURCE_FILE_NAME =>'*STMF',
SOURCE_STREAM_FILE =>'/usr/mytable_ddl');

GENERATE_SQL_OBJECTS procedure
The GENERATE_SQL_OBJECTS procedure generates the SQL data definition language (DDL) statements
required to recreate a set of database objects. The results are returned in the specified database source
file member, source stream file, or as a result set. The procedure will generate the objects so that
dependent objects are generated after depended on objects.

Database performance and query optimization 387


The database source file member or integrated file system (IFS) stream file will contain the generated
SQL statements. If the output source file is QTEMP/Q_GENSQOBJ, the source file is returned as a result
set as well.
Authorization:
When writing to a database source physical file the caller must have:
• *EXECUTE to the library containing the source physical file
• To add a member:
– *OBJOPR and *ADD to the source physical file
• To replace a member:
– *OBJOPR, *DELETE, *ADD, and either *OBJMGT or *OBJALTER to the source physical file
When writing to an IFS stream file:
• Execute (*X) data authority to each directory preceding the stream file being written and
• When the stream file exists:
– Write (*W) data authority to the stream file
• When the stream file does not exist:
– Write and Execute (*WX) authority to the parent directory of the stream file
To generate source for an object type, the following authorities are needed:
• TABLE, VIEW, CONSTRAINT, or TRIGGER
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *FILE object
• INDEX
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *FILE object, and
– *OBJOPR to the base *FILE object
• MASK or PERMISSION
– *EXECUTE and *OBJOPR to the library, and at least one of the following:
- *OBJOPR to the *FILE object
- QIBM_DB_SECADM function usage
• ALIAS
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *FILE object
• FUNCTION or PROCEDURE
– *OBJOPR to the library
• TYPE
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *SQLUDT object
• SCHEMA
– *OBJOPR and either *READ or *EXECUTE to the *LIB object
• SEQUENCE
– *EXECUTE and *OBJOPR to the library, and
– *USE to the *DTAARA object

388 IBM i: Performance and Query Optimization


• VARIABLE
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *SRVPGM object
• XSR
– *EXECUTE and *OBJOPR to the library, and
– *OBJOPR to the *SQLXSR object

Database performance and query optimization 389


GENERATE_SQL_OBJECTS ( system_table-name
SYSTEM_TABLE_NAME =>

, system-table-schema
SYSTEM_TABLE_SCHEMA =>

, database-source-file-name
DATABASE_SOURCE_FILE_NAME =>

, database-source-file-library-name
DATABASE_SOURCE_FILE_LIBRARY_NAME =>

, database-source-file-member
DATABASE_SOURCE_FILE_MEMBER =>

, severity-level
SEVERITY_LEVEL =>

, replace-option
REPLACE_OPTION =>

, statement-formatting-option
STATEMENT_FORMATTING_OPTION =>

, date-format
DATE_FORMAT =>

, date-separator
DATE_SEPARATOR =>

, time-format
TIME_FORMAT =>

, time-separator
TIME_SEPARATOR =>

, naming-option
NAMING_OPTION =>

, decimal-point
DECIMAL_POINT =>

, standards-option
STANDARDS_OPTION =>

, drop-option
DROP_OPTION =>

, message-level
MESSAGE_LEVEL =>

, comment-option
COMMENT_OPTION =>

, label-option
LABEL_OPTION =>

, header-option
HEADER_OPTION =>

, trigger-option
TRIGGER_OPTION =>

, constraint-option
CONSTRAINT_OPTION =>

, system-name-option
SYSTEM_NAME_OPTION =>

, privileges-option
PRIVILEGES_OPTION =>

, ccsid-option
CCSID_OPTION =>

, create-or-replace-option
CREATE_OR_REPLACE_OPTION =>

, obfuscate-option
OBFUSCATE_OPTION =>

, activate-access-control-option
ACTIVATE_ROW_AND_COLUMN_ACCESS_CONTROL_OPTION =>

, mask-and-permission-option
MASK_AND_PERMISSION_OPTION =>

, qualified-name-option
QUALIFIED_NAME_OPTION =>

, additional-index-option
ADDITIONAL_INDEX_OPTION =>

, index-instead-of-view-option
INDEX_INSTEAD_OF_VIEW_OPTION =>

, temporal-option
TEMPORAL_OPTION =>

, source-stream-file
SOURCE_STREAM_FILE =>

, source-stream-file-end-of-line
SOURCE_STREAM_FILE_END_OF_LINE =>

)
, source-stream-file-ccsid
SOURCE_STREAM_FILE_CCSID =>

The schema is QSYS2.

system-table- A character or graphic string expression that identifies the name of a table that contains
name the names and types of the database objects for which DDL will be generated. The

390 IBM i: Performance and Query Optimization


system name of the table must be specified. The name is case sensitive. Delimiters
must be specified if they are required. For example, a file with a name of "abc" must be
specified as "abc". A file with a name of ABC must be specified in upper case. Wildcard
characters are not supported.
The specified table must contain three columns that contain the names and types of
the objects for which DDL will be generated. The column names of the table must be
OBJECT_SCHEMA, OBJECT_NAME, and SQL_OBJECT_TYPE, in that order.
For example, create the table like this:

CREATE TABLE QTEMP.INORDER (OBJECT_SCHEMA VARCHAR(258),


OBJECT_NAME VARCHAR(258),
SQL_OBJECT_TYPE CHAR(10));

The contents of the columns must be specified according to the following rules for the
corresponding parameters in the QSQGNDDL API. Each row in the table must identify an
object that is distinct from every other object in the table.
OBJECT_SCHEMA Identifies the schema name of an object for which DDL will be
generated. The name must be delimited if delimiters are required
in an SQL statement. This name is ignored if the specified object
type is SCHEMA. *LIBL and *CURLIB are not allowed.
OBJECT_NAME Identifies the name of an object for which DDL will be generated.
The name must be delimited if delimiters are required in an SQL
statement. If the object type is a FUNCTION or PROCEDURE, this
name must be the specific name of the function or procedure. If
TABLE or VIEW is specified for the object type, the object name
must not identify an alias.
SQL_OBJECT_TYPE Identifies the SQL object type of an object for which DDL will be
generated.

ALIAS The object is an SQL alias.


CONSTRAINT The object attribute is a constraint.
FUNCTION The object is an SQL function.
INDEX The object is an SQL index.
MASK The object is an SQL column mask.
PERMISSION The object is an SQL row permission.
PROCEDURE The object is an SQL procedure.
SCHEMA The object is an SQL schema.
SEQUENCE The object is an SQL sequence.
TABLE The object is an SQL table or physical file.
TRIGGER The object attribute is a trigger.
TYPE The object is an SQL type.
VARIABLE The object is an SQL global variable.
VIEW The object is an SQL view or logical file.
XSR The object is an XML schema repository object.

system-table- A character or graphic string expression that identifies the name of the library of the
schema table that contains the names and types of the database objects for which DDL will
be generated. The system name of the schema must be specified. The name is case
sensitive. Delimiters must be specified if they are required. For example, a schema with

Database performance and query optimization 391


a name of "lib1" must be specified as "lib1". A schema with a name of LIB1 must be
specified in upper case. Wildcard characters are not supported. *LIBL and *CURLIB are
not allowed.
The default is QTEMP.

database- A character or graphic string expression that identifies the name of the source file that
source-file- contains the SQL statements generated by the procedure. The name must be a valid
name system name. The name is case sensitive. If delimiters are required for the name to be
valid, they must be specified. For example, a file with a name of "abc" must be specified
with the surrounding quotes. A file with a name of ABC must be specified in upper case.
The record length of the specified source file must be greater than or equal to 92.
Can contain the following special value:

*STMF The output is to be written to source-stream-file.

If database-source-file-name is not specified, Q_GENSQOBJ will be used.


database- A character or graphic string expression that identifies the name of the library
source-file- containing the source file that contains the SQL statements generated by the procedure.
library-name The name must be a valid system name. The name is case sensitive. If delimiters are
required for the name to be valid, they must be specified.
If database-source-file-library-name is not specified, QTEMP will be used.
database- A character or graphic string expression that identifies the name of the source file
source-file- member that contains the SQL statements generated by the procedure. The name must
member be a valid system name. The name is case sensitive. If delimiters are required for the
name to be valid, they must be specified.
If values are provided for database-source-file-library-name, database-source-file-
name, and database-source-file-member the object must exist.
If database-source-file-member is not specified, Q_GENSQOBJ will be used.

severity-level The severity level at which the operation fails. If errors occur that have a severity level
greater than this value, the operation ends. The valid values are in the range 0 through
39 inclusive. Any severity 40 error will cause the procedure to fail.
If severity-level is not specified, 39 will be used.
replace-option The replace option for the database source file member or source stream file. The valid
values are:

0 The resulting SQL statements are appended to the end of the database source file
member or source stream file.
1 The database source file member or source stream file is cleared prior to adding the
resulting SQL statements. If this option is chosen, the clear might happen even if an
error is returned from the procedure.

If replace-option is not specified, 1 will be used.


statement- The formatting option used in the generated SQL statements. The valid values are:
formatting-
option 0 No additional formatting characters are added to the generated SQL statements.
1 Additional end-of-line characters and tab characters are added to the generated
SQL statements.

If statement-formatting-option is not specified, 1 will be used.


date-format The date format used for date constants in a generated SQL CREATE TABLE statement.
The date format may not apply to date constants that are in ISO, EUR, USA,

392 IBM i: Performance and Query Optimization


or JIS format in a CREATE VIEW, CREATE TRIGGER, CREATE FUNCTION, CREATE
PROCEDURE, CREATE MASK, or CREATE PERMISSION.
If date-format is not specified, ISO will be used.
date- The date separator used for date constants in a generated SQL CREATE TABLE
separator statement. The date separator may not apply to date constants that are in ISO, EUR,
USA, or JIS format in a CREATE VIEW, CREATE TRIGGER, CREATE FUNCTION, CREATE
PROCEDURE, CREATE MASK, or CREATE PERMISSION statement.
If date-separator is not specified, - will be used.
time-format The format used for time constants in a generated SQL CREATE TABLE statement. The
time format may not apply to time constants that are in ISO, EUR, USA, or JIS format in
a CREATE VIEW, CREATE TRIGGER, CREATE FUNCTION, CREATE PROCEDURE, CREATE
MASK, or CREATE PERMISSION statement.
If time-format is not specified, ISO will be used.
time- The time separator used for time constants in a generated SQL CREATE TABLE
separator statement. The time separator may not apply to time constants that are in ISO, EUR,
USA, or JIS format in a CREATE VIEW, CREATE TRIGGER, CREATE FUNCTION, CREATE
PROCEDURE, CREATE MASK, or CREATE PERMISSION statement.
If time-separator is not specified, . will be used.
naming-option The naming convention used for qualified names in the generated SQL statements. The
valid values are:

SQL schema.table syntax


SYS library/file syntax

If naming-option is not specified, SQL will be used.


decimal-point The decimal point used for numeric constants. The valid values are:

. Period separator
, Comma separator

If decimal-point is not specified, . will be used.


standards- The standards option specifies whether the generated SQL statements should contain
option Db2 for i extensions or whether the statements should conform to the Db2 family SQL or
to the ANS and ISO SQL standards. The valid values are:

0 Db2 for i extensions may be generated in SQL statements.


1 The generated SQL statements must conform to SQL statements common to the
Db2 family.
2 The generated SQL statements must conform to the ANSI and ISO SQL standards.

If standards-option is not specified, 0 will be used.


drop-option The drop option specifies whether DROP (or ALTER) SQL statements should be
generated prior to the CREATE statement to drop the specified object. The valid values
are:

0 DROP statements should not be generated.


1 DROP statements should be generated.

If drop-option is not specified, 0 will be used.


message-level The severity level at which the messages are generated. If errors occur that have a
severity level greater than this value, a message is generated in the output. The valid

Database performance and query optimization 393


values are in the range 0 through 39 inclusive. The message level must be less than or
equal to the severity level.
If message-level is not specified, 0 will be used.
comment- The comment option specifies whether COMMENT SQL statements should be generated
option if a comment exists on the specified database object. If comments are not supported by
the specified database object, the comment option is ignored. The valid values are:

0 COMMENT SQL statements should not be generated.


1 COMMENT SQL statements should be generated. If the specified database object
type is a table or view, COMMENT SQL statements will also be generated for
columns of the table or view.
2 COMMENT SQL statements should be generated. If the specified database object
has no comment and its type is INDEX, SEQUENCE, TABLE, TYPE, VARIABLE, VIEW,
or XSR, the system object text will be used for the comment.
If the specified database object type is a table or view, COMMENT SQL statements
will also be generated for columns of the table or view.

If comment-option is not specified, 1 will be used.


label-option The label option specifies whether LABEL SQL statements should be generated if a label
exists on the specified database object. If labels are not supported by the specified
database object, the label option is ignored. The valid values are:

0 LABEL SQL statements should not be generated.


1 LABEL SQL statements should be generated. If the specified database object type
is a table or view, LABEL SQL statements will also be generated for columns of the
table or view.

If label-option is not specified, 1 will be used.


header-option The header option specifies whether a header should be generated prior to the first
generated statement. The header consists of comments that describe the version, date
and time, the relational database, and some of the options used to generate the SQL
statements. The valid values are:

0 A header should not be generated.


1 A header should be generated.

If header-option is not specified, 1 will be used.


trigger-option The trigger option specifies whether triggers should be generated when the object type
is a TABLE or VIEW. The valid values are:

0 Triggers should not be generated.


1 Triggers should be generated.

If trigger-option is not specified, 1 will be used.


constraint- The constraint option specifies whether constraints should be generated when the
option object type is a TABLE. The valid values are:

0 Constraints should not be generated.


1 Constraints should be generated.
2 Constraints should be generated as part of the CREATE TABLE statement.

If constraint-option is not specified, 1 will be used.

394 IBM i: Performance and Query Optimization


system-name- The system name option specifies whether a FOR SYSTEM NAME clause should be
option generated for the system name when it is different from the SQL name and the object
type is an INDEX, TABLE, VIEW, SEQUENCE, or VARIABLE. The valid values are:

0 A FOR SYSTEM NAME clause should not be generated.


1 A FOR SYSTEM NAME clause should be generated.

If system-name-option is not specified, 1 will be used.


privileges- The privileges option specifies whether GRANT SQL statements should be generated on
option the specified database object. If privileges are not supported by the specified database
object, the privileges option is ignored. The valid values are:

0 GRANT SQL statements should not be generated.


1 GRANT SQL statements should be generated.

If privileges-option is not specified, 1 will be used.


ccsid-option The CCSID option specifies whether the CCSID attribute should be generated for
column definitions when the object type is a TABLE. The valid values are:

0 CCSID attribute should not be generated.


1 CCSID attribute should be generated.

If ccsid-option is not specified, 1 will be used.


create-or- The create or replace option specifies whether CREATE OR REPLACE should be
replace-option generated for the specified database object on the CREATE statement. This option is
ignored if the specified database object does not support CREATE OR REPLACE. The
valid values are:

0 CREATE OR REPLACE should not be generated.


1 CREATE OR REPLACE should be generated.

If create-or-replace-option is not specified, 0 will be used.


obfuscate- The obfuscate option specifies whether an obfuscated SQL statement should be
option returned for SQL functions, SQL procedures, or SQL triggers that were not created using
obfuscated statements. This option is ignored if the standards option is not ‘0’. This
option is also ignored if the object is not an SQL function, procedure, or trigger. This
option is ignored if the object is already obfuscated. Setting Obfuscate option = 0 cannot
be used as a means of obtaining the unobfuscated SQL statement for an obfuscated
object. The valid values are:

0 An obfuscated statement should not be generated.


1 An obfuscated statement should be generated for SQL functions, SQL procedures,
or SQL triggers.

If obfuscate-option is not specified, 0 will be used.


activate- The activate row and column access control option specifies whether an ALTER TABLE
access- to activate row and column access control should be generated when the object type is
control-option a TABLE. This option is ignored if the standards option is not '0' or '1'. The valid values
are:

0 Activate row and column access control should not be generated.


1 Activate row and column access control should be generated.

If activate-access-control-option is not specified, 1 will be used.

Database performance and query optimization 395


mask-and- The mask and permission option specifies whether row permissions and column masks
permission- should be generated when the object type is a TABLE. This option is ignored if the
option standards option is not '0' or '1'. The valid values are:

0 Permissions and masks should not be generated.


1 Permissions and masks should be generated.

If mask-and-permission-option is not specified, 1 will be used.


qualified- The qualified name option specifies whether qualified or unqualified names should be
name-option generated for the specified database object. The valid values are:

0 Qualified object names should be generated. Unqualified names within the body of
SQL routines will remain unqualified.
1 Unqualified object names should be generated when a library is found which
matches the database object library name. Any SQL object or column reference
that is RDB qualified will be generated in its fully qualified form. For example, rdb-
name.schema-name.table-name and rdb-name.schema-name.table-name.column-
name references will retain their full qualification.

If qualified-name-option is not specified, 0 will be used.


additional- The additional index option specifies whether additional CREATE INDEX statements will
index-option be generated for DDS-created keyed physical or logical files. The valid values are:

0 Additional CREATE INDEX statements will not be generated.


1 An additional CREATE INDEX statement will be generated that matches the index
for a DDS-created keyed physical file. If the physical file has a PRIMARY KEY
constraint, a CREATE INDEX statement is not generated.
An additional CREATE INDEX statement will be generated that matches the index
for a DDS-created keyed logical file. If a value of ‘1’ is specified for the index instead
of view option, an additional CREATE INDEX statement is not generated. Additional
CREATE INDEX statements will also be generated that match the join indexes of a
DDS-created join logical file.

If additional-index-option is not specified, 0 will be used.


index-instead- The index instead of view option specifies whether a CREATE INDEX or CREATE VIEW
of-view-option statement will be generated for a DDS-created keyed logical file. The valid values are:

0 A CREATE VIEW statement will be generated.


1 A CREATE INDEX statement will be generated that matches the index for a DDS-
created keyed logical file.

If index-instead-of-view-option is not specified, 0 will be used.


temporal- The temporal option specifies whether a CREATE TABLE and an ALTER TABLE statement
option will be generated when the object type is a TABLE and the table is defined as a temporal
table. This option is ignored if the object is not a temporal table or if the standards
option is not ‘0’ or '1'. The valid values are:

0 A CREATE TABLE statement will be generated.


1 A CREATE TABLE statement will be generated and an ALTER TABLE statement will
be generated to add versioning.
2 Only an ALTER TABLE statement will be generated to add versioning.

If temporal-option is not specified, 0 will be used.

396 IBM i: Performance and Query Optimization


source- A character or graphic string expression that identifies the source stream file that
stream-file contains the SQL statements generated by the procedure. This parameter is ignored
unless database-source-file-name has a value of *STMF.
If the file does not exist, it will be created using the CCSID specified by source-stream-
file-ccsid. As lines are written to the file, source-stream-file-end-of-line determines the
end of line sequence, if any, to be appended to each line.
When source-stream-file is used, values provided for database-source-file-library-name
and database-source-file-member are ignored.
Writing to the QSYS.LIB file system is not supported.

source- A character or graphic string expression that defines the end of line character(s) which
stream-file- will be appended to the end of each line when writing to source-stream-file. The carriage
end-of-line return character is always X’0D’. Based on the CCSID of the source stream file, the line
feed character is X’25’ for an EBCDIC CCSID and X’0A’ for ASCII and UTF-8 CCSIDs. The
valid values are:

CR A carriage return is appended.


CRLF A carriage return and line feed are appended.
LF A line feed is appended.
LFCR A line feed and carriage return are appended.

If source-stream-file-end-of-line is not specified, CRLF will be used.


This parameter is ignored when writing to a source file.

source- An integer value that defines the CCSID to use if a new source stream file is created.
stream-file- If source-stream-file is specified and the source stream file does not exist, it will be
ccsid created with this CCSID value. A value of 0 indicates that the default job CCSID is to be
used. A CCSID of 65535 cannot be specified.
If source-stream-file-ccsid is not specified, 0 will be used.
This parameter is ignored when writing to a source file.

Notes
• If an error occurs while generating the DDL for an object, the source file or source stream file will
contain the error and processing will continue to the next object. After processing the last object, a
warning SQLSTATE '01H52' will be returned.
• Objects are generated in the following order:
1. Schemas
2. Types
3. Sequences
4. Aliases
5. Non-MQT tables and any constraints and indexes on those tables
6. Functions
7. Procedures
8. Variables
9. Views, DDS-created logical files and MQTs and any constraints and indexes on those tables
10. Triggers
11. Masks
12. Permissions

Database performance and query optimization 397


13. XSR objects

Restrictions
• One use of this procedure is to create a clone of a set of objects in another library by using
QUALIFIED_NAME_OPTION=>1, setting the current schema and path, and then running the generated
script.
– If a depended on object is not included in the list of objects for which DDL will be generated, errors
may occur when attempting to run the generated script. For example, if view V1 is based on table T1,
but only V1 is specified, the attempt to run the generated script will fail because T1 was not included.
– The QSQGNDDL API, on which this procedure is based, generates a qualified name in some cases.
Thus, it may be necessary to make minor modifications to the script prior to running it. For
more information see the Qualified name option parameter in Generate Data Definition Language
(QSQGNDDL) API.
• A function or procedure that has a parameter with a DEFAULT clause that references a variable, view, or
MQT will not create when running the generated script. This is because variables, views, and MQTs are
generated after functions and procedures. Note that references to variables, views, and MQTs within the
body of function or procedure are soft dependencies and will not prevent the create.
• A variable that contains a DEFAULT clause that references a view or MQT will not create when running
the generated script. This is because views and MQTs are generated after variables.

Examples
• Generate ordered DDL for the objects listed in the QTEMP.INORDER file.

CALL QSYS2.GENERATE_SQL_OBJECTS('INORDER', 'QTEMP');

RELATED_OBJECTS table function


The RELATED_OBJECTS table function returns a list of all objects that depend on the specified database
file, either directly or indirectly.
The list contains all objects that are directly dependent on the input database file. Each identified view
and global variable is processed recursively to obtain its dependents until no more dependents are found.
If the input file is an SQL alias, a program described file, or the file is not found, no rows are returned.
The dependency information is collected from the database cross reference tables and the SQL catalog.
Some dependencies might not be returned based on how the dependent object was specified in the
original statement. For example, if a CREATE FUNCTION statement references an unqualified table, the
dependency will not be complete in the SQL catalog view (SYSROUTINEDEP) and subsequently will not be
returned by this function.
Authorization: See Note below.

RELATED_OBJECTS ( library-name ,
LIBRARY_NAME =>

file-name )
FILE_NAME =>

The schema is SYSTOOLS.

library-name A character or graphic string expression that identifies the library that contains file-name.
It must exist on the current server.
file-name A character or graphic string expression that identifies the database file to list related
objects for. This must be the system name of the file.

398 IBM i: Performance and Query Optimization


The result of the function is a table containing rows with the format shown in the following table. All
columns are nullable.
Table 80. RELATED_OBJECTS table function

Column Name Data Type Description

SOURCE_SCHEMA_NAME VARCHAR(128) The name of the schema that contains SOURCE_SQL_NAME.

SOURCE_SQL_NAME VARCHAR(128) The name of the object that this row is dependent on.

SQL_OBJECT_TYPE VARCHAR(24) The SQL type of the dependent object.

ALIAS An SQL alias defined for


SOURCE_SQL_NAME

FOREIGN KEY The child table in a referential constraint


with SOURCE_SQL_NAME

FUNCTION A function that references


SOURCE_SQL_NAME

HISTORY TABLE A history table associated with the temporal


table defined by SOURCE_SQL_NAME

INDEX An SQL index defined on


SOURCE_SQL_NAME

KEYED LOGICAL A native keyed logical file defined on


FILE SOURCE_SQL_NAME

LOGICAL FILE A native logical file defined on


SOURCE_SQL_NAME

MASK A column mask on a column in


SOURCE_SQL_NAME or that references
SOURCE_SQL_NAME in its definition

MATERIALIZED A materialized query table that references


QUERY TABLE SOURCE_SQL_NAME

PERMISSION A row permission that is defined on


SOURCE_SQL_NAME or that references
SOURCE_SQL_NAME in its definition

PROCEDURE A procedure that references


SOURCE_SQL_NAME

TEXT INDEX An OmniFind text index built over


SOURCE_SQL_NAME

TRIGGER An SQL trigger that is defined on


SOURCE_SQL_NAME or that references
SOURCE_SQL_NAME in its definition

VARIABLE A global variable that references


SOURCE_SQL_NAME in its default
expression

VIEW A view that references SOURCE_SQL_NAME


in its definition

XML SCHEMA An XML schema that uses


SOURCE_SQL_NAME

SCHEMA_NAME VARCHAR(128) The SQL schema containing SQL_NAME.

SQL_NAME VARCHAR(128) The SQL name of the dependent object.


• When SQL_OBJECT_TYPE is FOREIGN KEY, this is the name of the
child table

LIBRARY_NAME VARCHAR(10) The system library name of the dependent object.


• When SQL_OBJECT_TYPE is TRIGGER, the library containing the
trigger program
Contains the null value when SQL_OBJECT_TYPE is FOREIGN KEY,
FUNCTION, PROCEDURE, and TEXT INDEX.

Database performance and query optimization 399


Table 80. RELATED_OBJECTS table function (continued)

Column Name Data Type Description

SYSTEM_NAME VARCHAR(279) The related system name of the dependent object.


• When SQL_OBJECT_TYPE is FOREIGN KEY, the constraint name
• When SQL_OBJECT_TYPE is FUNCTION or PROCEDURE, the
external name
• When SQL_OBJECT_TYPE is MASK or PERMISSION, the mask or
permission name
• When SQL_OBJECT_TYPE is TRIGGER, the name of the trigger
program
Contains the null value when SQL_OBJECT_TYPE is TEXT INDEX.

OBJECT_OWNER VARCHAR(10) The owner of the object. When SQL_OBJECT_TYPE is FUNCTION,


MASK, PERMISSION, PROCEDURE, TRIGGER, or VARIABLE this is the
object's definer.
Contains the null value when SQL_OBJECT_TYPE is FOREIGN KEY or
TEXT INDEX.

LONG_COMMENT VARGRAPHIC(2000) CCSID 1200 The SQL long comment for the object.
Contains the null value when the comment is not available.

OBJECT_TEXT VARGRAPHIC(50) CCSID 1200 The system text description for the object.
Contains the null value when the text is not available.

LAST_ALTERED TIMESTAMP The timestamp when the object was last altered. For objects that
cannot be altered, this is the create timestamp.
Contains the null value when SQL_OBJECT_TYPE is FOREIGN KEY.

Note
This procedure is provided in the SYSTOOLS schema as an example of how to use the SQL catalog to find
dependency information using an SQL function. Similar to other Db2 for i provided tools within SYSTOOLS,
the SQL source can be extracted and used as a model for building similar functions, or to create a
customized version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Examples
• List all the objects that are dependent on the ORDERS file in APPLIB.

SELECT * FROM TABLE(SYSTOOLS.RELATED_OBJECTS(


LIBRARY_NAME=>'APPLIB',
FILE_NAME =>'ORDERS'));

• List all the objects that are dependent on the ORDERS file in APPLIB. For each object, return how many
recursive steps were required to find the object.

SELECT LEVEL, RO.*


FROM (VALUES('APPLIB', 'ORDERS')) I(IN_LIB, IN_FILE),
TABLE (QSYS2.OBJECT_STATISTICS(IN_LIB, '*FILE', IN_FILE)),
TABLE(SYSTOOLS.RELATED_OBJECTS(IN_LIB, IN_FILE)) RO
START WITH SOURCE_SCHEMA_NAME = OBJLONGSCHEMA AND
SOURCE_SQL_NAME = OBJLONGNAME
CONNECT BY SOURCE_SQL_NAME = PRIOR SQL_NAME AND
SOURCE_SCHEMA_NAME = PRIOR SCHEMA_NAME
ORDER BY 1, 2, 3;

400 IBM i: Performance and Query Optimization


RESTART_IDENTITY procedure
The RESTART_IDENTITY procedure examines the source-table and determines the identity column and its
next value. The next value and column name are used to configure the target-table to use the same next
value.
Authorization: The caller must have:
• *EXECUTE authority on the library containing the table being modified, and
• *OBJALTER authority on the table

RESTART_IDENTITY ( source-schema
SOURCE_SYSTEM_TABLE_SCHEMA =>

, source-table ,
SOURCE_SYSTEM_TABLE_NAME =>

target-schema ,
TARGET_SYSTEM_TABLE_SCHEMA =>

target-table )
TARGET_SYSTEM_TABLE_NAME =>

The schema is QSYS2.

source- A character or graphic string for the schema name containing source-file. It must be a
schema system schema name.
source-table A character or graphic string for the table name that has the identity value to copy. It
must be a system table name. The table must contain an identity column.
target- A character or graphic string for the schema name containing target-table. It must be a
schema system schema name.
target-table A character or graphic string for the table name that is to have its identity column value
reset. It must be a system table name. The table must contain an identity column that
has the same name as the identity column in source-table.

Example
Set the identity column in NEWTABLE to have the same next value as the identity column in OLDTABLE

CALL QSYS2.RESTART_IDENTITY(SOURCE_SYSTEM_TABLE_SCHEMA => 'OLDLIB',


SOURCE_SYSTEM_TABLE_NAME => 'OLDTABLE',
TARGET_SYSTEM_TABLE_SCHEMA => 'NEWLIB',
TARGET_SYSTEM_TABLE_NAME => 'NEWTABLE')

SWAP_DYNUSRPRF procedure
The SWAP_DYNUSRPRF procedure switches the SQL DYNUSRPRF setting for a program or service
program. The possible values are *OWNER and *USER. Calling this procedure will change the value for a
program or service program to the opposite setting. The switch will be performed for all modules in an ILE
program or service program.
The following query shows the current value of the DYNUSRPRF setting for any modules that are part of
an ILE program or service program:

SELECT SQL_DYNAMIC_USER_PROFILE FROM QSYS2.BOUND_MODULE_INFO


WHERE PROGRAM_LIBRARY = 'MYLIB' AND PROGRAM_NAME = 'MYPGM';

Database performance and query optimization 401


For an OPM program, run the following query:

SELECT SQL_DYNAMIC_USER_PROFILE FROM QSYS2.PROGRAM_INFO


WHERE PROGRAM_LIBRARY = 'MYLIB' AND PROGRAM_NAME = 'MYPGM';

Authorization: The caller must have *ALLOBJ special authority or be authorized to the
QIBM_DB_SECADM function usage ID.

SWAP_DYNUSRPRF ( program-library
PROGRAM_LIBRARY =>

, program-name
PROGRAM_NAME =>

, program-type )
PROGRAM_TYPE =>

The schema is QSYS2.

program-library A character or graphic string containing the name of the library containing the
program. Can be one of the following special values:

*CURLIB The job's current library is used.


*LIBL The library list is used.

program-name A character or graphic string containing the program name.


program-type The object type for program-name.

*PGM The object is a program.


*SRVPGM The object is a service program.

Example
Switch the value of the dynamic user profile for program MYLIB/MYPGM.

CALL QSYS2.SWAP_DYNUSRPRF('MYLIB', 'MYPGM', '*PGM');

SYSFILES view
The SYSFILES view contains information about database files. Additional information is available in the
QSYS2.SYSTABLES view.
The information returned is similar to the detail seen from the Display File Description (DSPFD) command
and the Retrieve Database File Description (QDBRTVFD) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the file, and
• *OBJOPR authority to the file.
The following table describes the columns in the view. The schema is QSYS2.
Table 81. SYSFILES view

Column Name System Column Name Data Type Description

SYSTEM_TABLE_SCHEMA LIB_NAME VARCHAR(10) The library containing the file.

SYSTEM_TABLE_NAME FILE_NAME VARCHAR(10) The name of the file.

TABLE_SCHEMA TABSCHEMA VARCHAR(128) The SQL schema name of the library.

402 IBM i: Performance and Query Optimization


Table 81. SYSFILES view (continued)

Column Name System Column Name Data Type Description

TABLE_NAME TABNAME VARCHAR(128) The SQL name of the file.

IASP_NUMBER IASPNUMBER INTEGER The independent auxiliary storage pool (IASP) number.

TEXT_DESCRIPTION TEXT VARGRAPHIC(50) The descriptive text for the file.


CCSID 1200
Contains the null value if there is no descriptive text.
Nullable

NATIVE_TYPE DDS_TYPE VARCHAR(8) Type of file.

LOGICAL This is a DDS created logical file or an SQL view or


index.

PHYSICAL This is a physical file or an SQL table.

FILE_TYPE FILETYPE VARCHAR(6) Type of file.

DATA This is a data file.

SOURCE This is a source physical file.

SQL_OBJECT_TYPE SQL_TYPE VARCHAR(5) SQL object type.

Nullable INDEX This is an SQL index.

TABLE This is an SQL table.

VIEW This is an SQL view.

Contains the null value if this is not an SQL object.

LAST_ALTERED_TIMESTAMP ALTEREDTS TIMESTAMP(0) Timestamp when the file was last altered or created.

FILE_LEVEL_ID FILE_LVLID CHAR(13) File level identifier. This is the date of the file in
CYYMMDDHHMMSS format.

LEVEL_CHECK LVLCHK VARCHAR(3) Record format level check (LVLCHK).

NO The record format level identifiers are not checked when


the file is opened.

YES The record format level identifiers are checked when the
file is opened.
See Level checking for some additional information
about how level checking works.

FILE_OWNER OWNER VARCHAR(10) The owner of the object.

Nullable Contains the null value if the object owner is not available.

CREATE_PUBLIC_AUTHORITY PUB_AUTH VARCHAR(10) The public authority that the file was created with (AUT). This is
not the current public authority for the file.

*ALL Public all authority

*CHANGE Public change authority

*EXCLUDE Public exclude authority

*USE Public use authority

authorization-list- The name of the authorization list


name whose authority is used for the file.

NUMBER_MEMBERS MEMBERS INTEGER Number of members.

MAXIMUM_ MEMBERS MAXMBRS INTEGER Maximum members (MAXMBRS).

Nullable 1 to 32767 The maximum number of members for the file.

Contains the null value if no maximum is specified; 32767 is


used (*NOMAX).

MAXIMUM_RECORD_LENGTH RECLENGTH INTEGER Maximum record length. This is the length of the record in the
file's record format that contains the largest number of bytes.

NUMBER_KEY_FIELDS KEY_FLDS INTEGER Number of key fields for the file.

MAXIMUM_KEY_LENGTH KEY_LEN INTEGER Maximum key length for the file.

Database performance and query optimization 403


Table 81. SYSFILES view (continued)

Column Name System Column Name Data Type Description

TRIGGER_COUNT TRIG_CNT INTEGER Number of triggers.

CONSTRAINT_COUNT CONSTR_CNT INTEGER Number of constraints for the file.

Nullable Contains the null value if this is not a physical file.

NUMBER_BASED_ON_FILES BASE_FILES INTEGER Number of files directly referenced by a logical file, view, or
index.
Nullable
Contains the null value for physical files.

BASED_ON_FILES BASED_ON CLOB(35K) CCSID A list of files directly referenced by this logical file, view, or
1208 index.

Nullable This list is returned as an array within a JSON object. The array
is identified by BASED_ON_FILES. Each entry in the JSON array
identifies one file. Each array entry can contain information with
the following keys:
• LIBRARY
• FILE
• MEMBER
• LF_FORMAT
Contains the null value for physical files.

ALLOW_READ ALWREAD VARCHAR(3) Allow read operation.

NO Records are not allowed to be read from the file.

YES Records are allowed to be read from the file.

ALLOW_WRITE ALWWRITE VARCHAR(3) Allow write operation.

NO Records are not allowed to be written to the file.

YES Records are allowed to be written to the file.

ALLOW_UPDATE ALWUPD VARCHAR(3) Allow update operation (ALWUPD).

NO Records are not allowed to be updated in the file.

YES Records are allowed to be updated in the file.

ALLOW_DELETE ALWDLT VARCHAR(3) Allow delete operation (ALWDLT).

NO Records are not allowed to be deleted from the file.

YES Records are allowed to be deleted from the file.

MAXIMUM_FILE_WAIT_TIME WAITFILE INTEGER Maximum file wait time (WAITFILE).

-1 The default wait time specified in the class


description is used (*CLS).

0 The program does not wait for the file; an


immediate allocation is required (*IMMED).

1 through The maximum number of seconds a program


32767 waits for the file.

MAXIMUM_RECORD_WAIT_TIME WAITRCD INTEGER Maximum record wait time (WAITRCD).

-2 The default wait time allowed by the system is


used. This is 32767 seconds (*NOMAX).

-1 The program does not wait for the record, an


immediate allocation is required (*IMMED).

1 through The maximum number of seconds a program


32767 waits for the record.

404 IBM i: Performance and Query Optimization


Table 81. SYSFILES view (continued)

Column Name System Column Name Data Type Description

FORCE_WRITE_RATIO FRCRATIO INTEGER Records to force a write (FRCRATIO).

Nullable 1 through When the cumulative count of inserted,


32767 updated, and deleted records has reached
this value, the changed records are forced to
storage.

Contains the null value is there is no force write ratio.

SELECT_OMIT SELECTOMIT VARCHAR(3) Select/omit setting.

NO The file is not a select/omit logical file.

YES The file is a select/omit logical file.

PROGRAM_DESCRIBED PGM_DESC VARCHAR(3) Program described file setting.

NO The file is not program described.

YES The file is program described.

DISTRIBUTED DIST_FILE VARCHAR(3) Distributed file setting.

NO The file is not distributed.

YES The file is distributed.

FILE_VRM FILE_VRM CHAR(6) File version, release, and modification level. VxRyMz, where x is
the version, y the release, and z the modification level. This is
the release where the file was created.

EARLIEST_POSSIBLE_RELEASE MINRLS CHAR(6) Earliest supported version, release, and modification level. New
database support used in the file will prevent the file from being
Nullable saved to a prior version, release, and modification level. The
value is formatted as VxRyMz, where x is the version, y the
release, and z the modification level.
Contains the null value if the value is prior to V2.

ALLOW_NULL_KEYS ALWNULLK VARCHAR(3) Allow null value key setting (ALWNULL).

Nullable NO Null value keys are not allowed.

YES Null value keys are allowed.

Contains the null value if ACCESS_PATH_KEYED is NO.

ALLOW_NULL_DATA ALWNULLD VARCHAR(3) Allow null value data (ALWNULL).

NO The file record format(s) do not allow null value fields.

YES The file record format(s) allow null value fields.

PRIMARY_KEY PRIKEY VARCHAR(3) Primary key (*PRIKEY).

NO The access path for the file is not a primary key.

YES The access path for the file is a primary key.

UNIQUE_CONSTRAINT UNQCST VARCHAR(3) Unique constraint.

NO The access path for the file is not a unique constraint.

YES The access path for the file is a unique constraint.

VOLATILE VOLATILE VARCHAR(3) SQL volatile table setting.

NO The file is not an SQL volatile table.

YES The file is an SQL volatile table.

KEEP_IN_MEMORY KEEPINMEM VARCHAR(3) The memory preference of the file.

NO The file does not have the keep in memory indication


set.

YES The file has the keep in memory indication set.

Database performance and query optimization 405


Table 81. SYSFILES view (continued)

Column Name System Column Name Data Type Description

MEDIA_PREFERENCE UNIT VARCHAR(4) Preferred storage unit for the file (UNIT).

*ANY No storage media is preferred. Storage will be


allocated from any available storage media.

*SSD Solid state disk storage media is preferred. Storage


may be allocated from solid state disk storage media,
if available.

SOURCE_FILE_LIBRARY SRCLIB VARCHAR(10) Library containing SOURCE_FILE.

Nullable Contains the null value if a source file was not used.

SOURCE_FILE SRCFILE VARCHAR(10) Name of the source file containing the DDS used to create the
file.
Nullable
Contains the null value if a source file was not used.

SOURCE_FILE_MEMBER SRCMBR VARCHAR(10) Source file member name within SOURCE_FILE used to create
the file.
Nullable
Contains the null value if a source file was not used.

ACCESS_PATH_KEYED ACCESSPATH VARCHAR(3) Whether the file has a keyed sequence access path.

NO The file does not have a keyed sequence access path.


The file is processed using arrival sequence.

YES The file has a keyed sequence access path.

ACCESS_PATH_TYPE AP_TYPE VARCHAR(14) Access path type.

Nullable EVI Encoded vector with a 1-, 2-, or 4-byte vector.

KEYED FCFO Keyed sequence access path with duplicate


keys allowed. Duplicate keys are accessed in
first-changed-first-out (FCFO) order.

KEYED FIFO Keyed sequence access path with duplicate


keys allowed. Duplicate keys are accessed in
first-in-first-out (FIFO) order.

KEYED LIFO Keyed sequence access path with duplicate


keys allowed. Duplicate keys are accessed in
last-in-first-out (LIFO) order.

KEYED NO Keyed sequence access path with duplicate


ORDER keys allowed. No order is guaranteed when
accessing duplicate keys.

KEYED Keyed sequence access path with no


UNIQUE duplicate keys allowed (UNIQUE).

Contains the null value if ACCESS_PATH_KEYED is NO.

ACCESS_PATH_MAINTENANCE MAINT VARCHAR(6) Access path maintenance (MAINT).

Nullable *DLY Delayed maintenance

*IMMED Immediate maintenance

*REBLD Rebuild maintenance

Contains the null value if ACCESS_PATH_KEYED is NO.

ACCESS_PATH_SIZE ACCPTHSIZ VARCHAR(7) Access path size (ACCPTHSIZ).

Nullable *MAX1TB All access paths associated with this file will be
allowed to occupy a maximum of 1 terabyte (1
099 511 627 776 bytes) of auxiliary storage

*MAX4GB All access paths associated with this file will be


allowed to occupy a maximum of 4 gigabytes (4
294 966 272 bytes) of auxiliary storage.

Contains the null value if ACCESS_PATH_KEYED is NO.

406 IBM i: Performance and Query Optimization


Table 81. SYSFILES view (continued)

Column Name System Column Name Data Type Description

LOGICAL_PAGE_SIZE PAGESIZE INTEGER Access path page size.

Nullable -1 Access path is a 4 gigabyte access path

0 System determines page size from the key length of the


access path

8 Page size is 8 kilobytes

16 Page size is 16 kilobytes

32 Page size is 32 kilobytes

64 Page size is 64 kilobytes

128 Page size is 128 kilobytes

256 Page size is 256 kilobytes

512 Page size is 512 kilobytes

Contains the null value if ACCESS_PATH_KEYED is NO.

FORCE_KEYED_ACCESS_PATH FRCACCPTH VARCHAR(3) Force keyed access path (FRCACCPTH).

Nullable NO The access path and changed records are not forced to
auxiliary storage when the access path is changed.

YES The access path and changed records are forced to


auxiliary storage when the access path is changed
(*YES).

Contains the null value if ACCESS_PATH_KEYED is NO.

ACCESS_PATH_JOURNALED JOURNALED VARCHAR(3) Access path journaled.

Nullable NO The access path is not journaled.

YES The access path is journaled.

Contains the null value if ACCESS_PATH_KEYED is NO.

ACCESS_PATH_RECOVERY RECOVER VARCHAR(7) Access path recovery (RECOVER).

Nullable *AFTIPL The file access path is built after the IPL is
completed.

*IPL The file access path is built during the IPL.

*NO The file access path is built when the file is next
opened.

Contains the null value if ACCESS_PATH_KEYED is NO.

SRTSEQ_IND SRTSEQ_IND INTEGER Sort sequence table (SRTSEQ) indicators.

1 No sort sequence table is used for the file, and the


hexadecimal value of the characters will be used to
determine the sort sequence (*HEX).

2 A sort sequence table was specified for the file.

3 No sort sequence table for the file; however, an alternate


collating sequence table was specified.

SORT_SEQUENCE_LIBRARY SRTSEQ_LIB VARCHAR(10) The library containing the sort sequence table or alternate
collating sequence table. Can contain the special value *LIBL.
Nullable
Contains the null value if SRTSEQ_IND is 1 or if there is no
library.

SORT_SEQUENCE SRTSEQ VARCHAR(10) The sort sequence table or alternate collating sequence table
associated with the file.
Nullable
Contains the null value if SRTSEQ_IND is 1.

LANGUAGE_IDENTIFIER LANGID CHAR(3) Language identifier (LANGID).

Nullable Contains the null value if there is no language identifier.

Database performance and query optimization 407


Table 81. SYSFILES view (continued)

Column Name System Column Name Data Type Description

ROUNDING_MODE DECFLTRND VARCHAR(8) Rounding mode to be used for decimal floating point
(DECFLOAT) calculations.
Nullable
CEILING

DOWN

FLOOR

HALFDOWN

HALFEVEN

HALFUP

UP

Contains the null value if the file has no decimal floating point
fields or this is not an SQL view, SQL index with a derived key
expression, SQL materialized query table, or logical file.

DECFLOAT_WARNINGS DECFLTWRN VARCHAR(3) Indicates whether warnings should be returned from decimal
floating point calculations.
Nullable
NO Warnings are not returned.

YES Warnings are returned.

Contains the null value if the file has no decimal floating point
fields or this is not an SQL view, SQL index with a derived key
expression, SQL materialized query table, or logical file.

NUMBER_RECORD_FORMATS FORMATS INTEGER Total number of record formats.

FORMAT_LEVEL_ID FMTLVLID CHAR(13) The record format level ID.

Nullable Contains the null value if file has more than one format or if no
value is available.

FORMAT_NAME FMT_NAME VARCHAR(10) The name of the record format.

Nullable Contains the null value if file has more than one format.

RECORD_LENGTH RCD_LEN INTEGER The length of the record format.

Nullable Contains the null value if file has more than one format.

NUMBER_FIELDS FIELDS INTEGER The number of fields in the record format.

Nullable Contains the null value if file has more than one format.

COMMON_CCSID CCSID INTEGER The CCSID used when all fields with a character, open, and
graphic data type use the same CCSID.
Nullable
Contains the null value if file has more than one format or if all
character, open, and graphic fields do not use the same CCSID.

CONTAINS_EXPLICIT_CCSID EXPLICIT VARCHAR(3) Explicit CCSID setting.

Nullable NO A CCSID was not specified for any character type fields
in the format.

YES A CCSID was specified for one or more character type


fields in the format.

Contains the null value if file has more than one format.

CONTAINS_MULTIPLE_CCSIDS MULTIPLE VARCHAR(3) Multiple CCSID setting.

NO The file has only one CCSID for its character type fields
or the file has no character type fields.

YES The file has more than one CCSID for its character type
fields

408 IBM i: Performance and Query Optimization


Table 81. SYSFILES view (continued)

Column Name System Column Name Data Type Description

CONTAINS_UNICODE UNICODE VARCHAR(3) Format contains UTF-8, UTF-16, or UCS-2 fields.

Nullable NO The file record format does not contain UTF-8, UTF-16,
or UCS-2 fields.

YES The file record format contains UTF-8, UTF-16, or UCS-2


fields.

Contains the null value if file has more than one format.

CONTAINS_VARYING_LENGTH VARLEN VARCHAR(3) File contains variable length fields (VARLEN).

NO The file record format does not contain variable length


fields.

YES The file record format contains variable length fields.

CONTAINS_DATETIME DATETIME VARCHAR(3) File contains date/time/timestamp fields.

NO The file record format does not contain date, time, or


timestamp fields.

YES The file record format contains date, time, or timestamp


fields.

CONTAINS_GRAPHIC GRAPHIC VARCHAR(3) File contains graphic fields.

NO The file record format does not contain graphic fields.

YES The file record format contains graphic fields.

CONTAINS_LOB LOB VARCHAR(3) File contains large object fields. These are the SQL data types
character large object (CLOB), double-byte character large
object (DBCLOB), and binary large object (BLOB).

NO The file record format does not have a large object field.

YES The file record format has a large object field.

CONTAINS_ROWID ROWID VARCHAR(3) File contains ROWID fields.

NO The file record format does not have a ROWID column.

YES The file record format has a ROWID column.

CONTAINS_UDT UDT VARCHAR(3) File contains user-defined type fields.

NO The file record format does not have a user-defined type


field.

YES The file record format has a user-defined type field.

CONTAINS_DATALINK DATALINK VARCHAR(3) File contains DataLink fields.

NO The file record format does not have a DataLink field.

YES The file record format has a DataLink field.

CONTAINS_DATALINK_ DATALINKFL VARCHAR(3) File contains DataLink with FILE LINK CONTROL fields.
FILE_LINK_CONTROL
NO The file record format does not have a DataLink field
with FILE LINK CONTROL.

YES The file record format has a DataLink field with FILE
LINK CONTROL.

CONTAINS_NULL NULLABLE VARCHAR(3) File contains null capable fields.

Nullable NO The file record format does not have any null capable
fields.

YES The file record format has null capable fields.

Contains the null value if file has more than one format.

Database performance and query optimization 409


Table 81. SYSFILES view (continued)

Column Name System Column Name Data Type Description

CONTAINS_DEFAULT DFT VARCHAR(3) The physical file format contains fields with explicit default
values.
Nullable
NO The file record format does not have any fields with
explicit default values.

YES The file record format has fields with explicit default
values.

Contains the null value if file has more than one format.

CONTAINS_IDENTITY IDENTITY VARCHAR(3) File contains an identity column.

NO The file record format does not have an identity column.

YES The file record format has an identity column.

CONTAINS_ROW_CHANGE_ ROW_CHANGE VARCHAR(3) File contains a row change timestamp column.


TIMESTAMP
NO The file record format does not have a row change
timestamp column.

YES The file record format has a row change timestamp


column.

CONTAINS_USER_DEFINED_ UDF VARCHAR(3) File contains a user-defined function.


FUNCTION
NO The file does not use a user-defined function.

YES The file uses a user-defined function.

Values for the following columns are returned when NATIVE_TYPE is PHYSICAL. Otherwise, the columns will contain the null value.

ALLOCATE_STORAGE ALLOCATE VARCHAR(3) The allocate storage setting (ALLOCATE).

Nullable NO New members added to the file allow the system


to determine storage space that is allocated for the
member (ALLOCATE(*NO))

YES New members added to the file use the initial number of
records to determine storage space that is allocated for
the member (ALLOCATE(*YES)).

CONTIGUOUS_STORAGE CONTIG VARCHAR(3) The contiguous storage setting (CONTIG).

Nullable NO Storage should not be attempted to be allocated


contiguously (CONTIG(*NO)).

YES Storage should be attempted to be allocated


contiguously (CONTIG(*YES)).

Contains the null value if ALLOCATE_STORAGE is NO.

MAXIMUM_DELETED_PERCENTAGE DLTPCT INTEGER Maximum percentage of deleted records allowed (DLTPCT).

Nullable 1 to 100 The threshold percentage of deleted records a


member can contain before a message is sent to
the history log.
See Deleted records for additional information.

Contains the null value if the number of deleted records is not


checked when the member is closed (*NONE).

INITIAL_RECORDS SIZE_INIT INTEGER Initial number of records (SIZE). This is the number of records
that can be inserted before an automatic extension occurs.
Nullable
Contains the null value if the number of records that can be
inserted into each member is not limited by the user. The system
determines the maximum member size (*NOMAX).

INCREMENT_RECORDS SIZE_INCR INTEGER Increment number of records (SIZE). This is the maximum
number of records that can be inserted into the member after
Nullable an automatic extension occurs.
Contains the null value when INITIAL_RECORDS is null.

410 IBM i: Performance and Query Optimization


Table 81. SYSFILES view (continued)

Column Name System Column Name Data Type Description

MAXIMUM_INCREMENTS SIZE_MAX INTEGER Maximum number of increments (SIZE). This is the maximum
number of automatic extensions that can be made to the
Nullable member.
Contains the null value when INITIAL_RECORDS is 0.

REUSE_DELETED_RECORDS REUSEDLT VARCHAR(3) Reuse deleted records (REUSEDLT).

Nullable NO Deleted records are not reused on subsequent writes or


inserts.

YES Deleted records can be reused on subsequent writes or


inserts.

MATERIALIZED_QUERY_TABLE MQT VARCHAR(3) SQL materialized query table setting.

Nullable NO This is not an SQL materialized query table.

YES This is an SQL materialized query table.

PARTITIONED_TABLE PARTITION VARCHAR(3) Partitioned table setting.

Nullable NO This is not a partitioned table.

YES This is a partitioned table.

ROW_AND_COLUMN_ACCESS_ RCAC VARCHAR(3) Row and column access control setting.


CONTROL Nullable NO Access controls are not defined for the file.

YES Access controls are defined for the file.


The QSYS2.SYSCONTROLS view contains detailed
information about row and column access controls.

Values for the following columns are returned when NATIVE_TYPE is LOGICAL. Otherwise, the columns will contain the null value.

TOTAL_SELECT_OMIT TOTAL_SO INTEGER Total number of select/omit statements for all record formats.

Nullable

FMTSLR_LIBRARY FMTSLR_LIB VARCHAR(10) Record format selector program library (FMTSLR)

Nullable Contains the null value if there is no record format selector


program.

FMTSLR_PROGRAM FMTSLR_PGM VARCHAR(10) Record format selector program (FMTSLR)

Nullable Contains the null value if there is no record format selector


program.

IS_JOIN_LOGICAL JFILE VARCHAR(3) Join logical file setting (JFILE).

Nullable NO The file is not a join logical file.

YES The file is a join logical file.

DYNAMIC_SELECTION DYNSLT VARCHAR(3) Dynamic selection setting (DYNSLT).

Nullable NO The selection and omission tests specified for the file
are done when the access path is updated.

YES The selection and omission tests specified for the file
are done when the file is read.

WITH_CHECK_OPTION CHECK VARCHAR(8) With check option.

Nullable CASCADED The cascaded check option was specified.

NO No check option was specified or this is not an


SQL view.

LOCAL The local check option was specified.

Database performance and query optimization 411


Table 81. SYSFILES view (continued)

Column Name System Column Name Data Type Description

PHYSICAL_LOB PF_LOB VARCHAR(3) Whether this logical file has no large object fields, but the based-
on physical file has a large object field.
Nullable
NO The logical file and based-on physical file either both
have large object fields or both do not.

YES The logical file has no large object fields, but the based-
on physical file has a large object field.

PHYSICAL_DATALINK PF_DATALNK VARCHAR(3) Whether this logical file has no DataLink fields, but the based-on
physical file has a DataLink field.
Nullable
NO The logical file and based-on physical file either both
have DataLink fields or both do not.

YES The logical file has no DataLink fields, but the based-on
physical file has a DataLink field.

INDEX_COLUMN_IS_EXPRESSION IXEXP VARCHAR(3) If the SQL index key column is an expression.

Nullable NO The key column is not an expression or this is not an SQL


index.

YES The key column is an expression.

INDEX_EXPRESSION_HAS_UDF IXEXPUDF VARCHAR(3) If the SQL index key column is an expression and the expression
contains a user-defined function (UDF).
Nullable
NO The key column is not an expression or the expression
does not contain a user-defined function, or this is not
an SQL index.

YES The key column is an expression and the expression


contains a UDF.

INDEX_HAS_SEARCH_CONDITION SPARSE VARCHAR(3) If the index has a search condition.

Nullable NO The index does not have a search condition, or this is not
an SQL index

YES The index has a search condition.

INDEX_SEARCH_CONDITION_ SPARSE_UDF VARCHAR(3) If the index search condition contains a user-defined function.
HAS_UDF Nullable NO The index is not sparse or does not contain a user-
defined function, or this is not an SQL index

YES The index is sparse and the search condition contains a


UDF.

Examples
• Examine all the files in APPLIB1.

SELECT * FROM QSYS2.SYSFILES WHERE LIB_NAME = 'APPLIB1';

• List the files that native logical files in APPLIB1 are based on.

WITH BASED_ONS (LF_NAME, BASED_ON_NAMES) AS (


SELECT TABLE_NAME, BASED_ON_FILES
FROM QSYS2.SYSFILES
WHERE SYSTEM_TABLE_SCHEMA = 'APPLIB1' AND
NATIVE_TYPE = 'LOGICAL' AND
SQL_OBJECT_TYPE IS NULL
)
SELECT DISTINCT LF_NAME, LIBRARY AS BASED_ON_LIBRARY, FILE AS BASED_ON_FILE
FROM BASED_ONS, JSON_TABLE(
BASED_ON_NAMES,
'lax $.BASED_ON_FILES'
COLUMNS(
LIBRARY CHAR(10), FILE CHAR(10)
))
order by 1, 2, 3;

412 IBM i: Performance and Query Optimization


SYSMEMBERSTAT view
The SYSMEMBERSTAT view contains one row for every table partition or table member, including rows for
program described files.
The following table describes the columns in the SYSMEMBERSTAT view:
Table 82. SYSMEMBERSTAT view

System Column
Column name Name Data Type Description

TABLE_SCHEMA TABSCHEMA VARCHAR(128) Name of the SQL schema that contains the table.

TABLE_NAME TABNAME VARCHAR(128) Name of the table.

SYSTEM_TABLE_SCHEMA SYS_DNAME VARCHAR(10) System schema name.

SYSTEM_TABLE_NAME SYS_TNAME VARCHAR(10) System table name.

SYSTEM_TABLE_MEMBER SYS_MNAME VARCHAR(10) System member name.

SOURCE_TYPE SRCTYPE VARCHAR(10) Source type of a source member.

Nullable Contains the null value if the table is not a source file.

LAST_SOURCE_UPDATE_TIMESTAMP LASTSRCUPD TIMESTAMP Last source change timestamp to a source member.

Nullable Contains the null value if the table is not a source file.

TEXT_DESCRIPTION TEXT VARGRAPHIC(50) Text description for the member or partition.


CCSID 1200
Contains the null value if there is no text description
Nullable for the member.

CREATE_TIMESTAMP CREATED TIMESTAMP Create timestamp of the member or partition.

LAST_CHANGE_TIMESTAMP LASTCHG TIMESTAMP Timestamp of the last change that occurred to the
member or partition.

LAST_SAVE_TIMESTAMP LASTSAVE TIMESTAMP Timestamp of the last save of the member or


partition.
Nullable
Contains the null value if the member or partition has
never been saved.

LAST_RESTORE_TIMESTAMP LASTRST TIMESTAMP Timestamp of the last restore of the member or


partition.
Nullable
Contains the null value if the member or partition has
never been restored.

LAST_USED_TIMESTAMP LASTUSED TIMESTAMP Timestamp of the last time the member or partition
was used directly by an application for native record
Nullable I/O or SQL operations.
Contains the null value if the member or partition has
never been used.

DAYS_USED_COUNT DAYSUSED INTEGER The number of days the member or partition was
used directly by an application for native record I/O
or SQL operations since the last time the usage
statistics were reset. If the member or partition
has never been used since the last time the usage
statistics were reset, contains 0.

LAST_RESET_TIMESTAMP LASTRESET TIMESTAMP The timestamp of the last time the usage statistics
were reset for the table. For more information see the
Nullable Change Object Description (CHGOBJD) command.
Contains the null value if the member or partition's
last used timestamp has never been reset.

TABLE_PARTITION TABPART VARCHAR(128) Name of the table member or partition.

PARTITION_TYPE PARTTYPE CHAR(1) The type of the table partitioning:

blank The table is not partitioned.

H This is data hash partitioning.

R This is data range partitioning.

D This is distributed database hash


partitioning.

Database performance and query optimization 413


Table 82. SYSMEMBERSTAT view (continued)

System Column
Column name Name Data Type Description

PARTITION_NUMBER PARTNBR INTEGER The partition number of this partition.

Nullable Contains the null value if the table is a distributed


table.

NUMBER_DISTRIBUTED_PARTITIONS DSTPARTS INTEGER If the table is a distributed table, contains the total
number of partitions.
Nullable
Contains the null value if the table is not a distributed
table.

NUMBER_PARTITIONING_KEYS NBRPKEYS INTEGER The number of partitioning keys.

Nullable Contains the null value if the table is not partitioned.

PARTITIONING_KEYS PARTKEYS VARCHAR(2880) The list of partitioning keys.

Nullable Contains the null value if the table is not partitioned.

LOWINCLUSIVE LOWINCL CHAR(1) Indicates whether the low key value for the partition
is inclusive.
Nullable
N The low key value is not inclusive.

Y The low key value is inclusive.

Contains the null value if the table is not partitioned


by range.

LOWVALUE LOWVALUE VARGRAPHIC(1024) A string representation of the low key value for a
CCSID 1200 range partition.

Nullable Contains the null value if the table is not partitioned


by range.

HIGHINCLUSIVE HIGHINCL CHAR(1) Indicates whether the high key value for the partition
is inclusive.
Nullable
N The high key value is not inclusive.

Y The high key value is inclusive.

Contains the null value if the table is not partitioned


by range.

HIGHVALUE HIGHVALUE VARGRAPHIC(1024) A string representation of the high key value for a
CCSID 1200 range partition.

Nullable Contains the null value if the table is not partitioned


by range.

NUMBER_ROWS CARD BIGINT Number of valid rows in the table member or


partition.

NUMBER_PAGES FPAGES BIGINT Number of 64K pages in the partition's data.

OVERFLOW OVERFLOW BIGINT The estimated number of rows that have overflowed
to variable length segments. If the table does not
contain variable length or LOB columns, contains 0.

AVGROWSIZE AVGROWSIZE BIGINT Average length (in bytes) of a row in this table. If the
table has variable length or LOB columns, contains
-1.

NUMBER_DELETED_ROWS DELETED BIGINT Number of deleted rows in the table member or


partition.

DATA_SIZE SIZE BIGINT Total size (in bytes) of the data space in the member
or partition.

VARIABLE_LENGTH_SIZE VLSIZE BIGINT Size (in bytes) of the variable-length data space
segments in the member or partition.

VARIABLE_LENGTH_SEGMENTS VLSEGMENTS BIGINT The number of variable-length data space segments


in the member or partition.

COLUMN_STATS_SIZE CSTATSSIZE BIGINT Size (in bytes) of the column statistics in the member
or partition.

MAINTAINED_TEMPORARY_INDEX_SIZE MTISIZE BIGINT Size (in bytes) of all maintained temporary indexes
over the member or partition.

414 IBM i: Performance and Query Optimization


Table 82. SYSMEMBERSTAT view (continued)

System Column
Column name Name Data Type Description

NUMBER_DISTINCT_INDEXES DISTINCTIX INTEGER The number of distinct indexes built over the member
or partition. This does not include maintained
temporary indexes.

OPEN_OPERATIONS OPENS BIGINT Number of full opens of the member or partition since
the last IPL.

CLOSE_OPERATIONS CLOSES BIGINT Number of full closes of the member or partition


since the last IPL.

INSERT_OPERATIONS INSERTS BIGINT Number of insert operations for the member or


partition since the last IPL.

BLOCKED_INSERT_OPERATIONS BLKIOPS BIGINT Number of blocked insert operations for the member
or partition since the last IPL.

BLOCKED_INSERT_ROWS BLKIROW BIGINT Number of rows inserted with blocked insert


operations for the member or partition since the last
IPL.

UPDATE_OPERATIONS UPDATES BIGINT Number of update operations for the member or


partition since the last IPL.

DELETE_OPERATIONS DELETES BIGINT Number of delete operations for the member or


partition since the last IPL.

CLEAR_OPERATIONS DSCLEARS BIGINT Number of clear operations (CLRPFM operations) for


the member or partition since the last IPL.

COPY_OPERATIONS DSCOPIES BIGINT Number of data space copy operations (certain


CPYxxx operations) for the member or partition since
the last IPL.

REORGANIZE_OPERATIONS DSREORGS BIGINT Number of data space reorganize operations (non-


interruptible RGZPFM operations) for the member or
partition since the last IPL.

INDEX_BUILDS DSINXBLDS BIGINT Number of creates or rebuilds of indexes that


reference the member or partition since the last IPL.
This does not include maintained temporary indexes.

LOGICAL_READS LGLREADS BIGINT Number of logical read operations for the member or
partition since the last IPL.

PHYSICAL_READS PHYREADS BIGINT Number of physical read operations for the member
or partition since the last IPL.

SEQUENTIAL_READS SEQREADS BIGINT Number of sequential read operations for the


member or partition since the last IPL.

RANDOM_READS RANREADS BIGINT Number of random read operations for the member
or partition since the last IPL.

NEXT_IDENTITY_VALUE NEXTVALUE DECIMAL(31,0) The next identity value. In some cases, this value may
be an estimate.
Nullable
Contains the null value if the table does not have an
identity column.

KEEP_IN_MEMORY KEEPINMEM CHAR(1) Indicates whether the partition should be kept in


memory:

0 No memory preference.

1 The partition should be kept in memory, if


possible.

MEDIA_PREFERENCE MEDIAPREF SMALLINT Indicates the media preference of the partition:

0 No media preference.

255 The partition should be allocated on Solid


State Disk (SSD), if possible.

VOLATILE VOLATILE CHAR(1) Indicates whether the table is volatile.

0 Table is not volatile.

1 Table is volatile.

Database performance and query optimization 415


Table 82. SYSMEMBERSTAT view (continued)

System Column
Column name Name Data Type Description

PARTIAL_TRANSACTION PARTIALTX CHAR(1) Indicates whether the partition contains a partial


transaction:

N The partition does not contain a partial


transaction.

Y The partition was saved while active with a


partial transaction.
A subsequent restore of the partition contains
the partial transaction. The user should apply
changes from the journal to complete the
transaction.

R A rollback abnormally ended prior to


completion.
This left the partition with a partial set of rolled
back rows.

APPLY_STARTING_RECEIVER APYRCVLIB VARCHAR(10) The library containing the starting journal receiver.
_LIBRARY Nullable Contains the null value if
APPLY_STARTING_RECEIVER is null.

APPLY_STARTING_RECEIVER APYRCVNAME VARCHAR(10) Indicates that the partition was saved and
subsequently restored. If the table was journaled
Nullable when the partition was saved, the starting journal
receiver name will indicate the journal receiver to
start with if APYJRNCHG is then used.
Contains the null value if PARTIAL_TRANSACTION
has a value of R. Once an APYJRNCHG is performed,
the apply information is cleared.

Example
Examine some statistical information for all members of all files in APPLIB1.

SELECT TABLE_NAME, SYSTEM_TABLE_MEMBER, NUMBER_ROWS, NUMBER_DELETED_ROWS, LAST_USED_TIMESTAMP


FROM QSYS2.SYSMEMBERSTAT
WHERE TABLE_SCHEMA = 'APPLIB1';

VALIDATE_DATA, VALIDATE_DATA_FILE, and VALIDATE_DATA_LIBRARY


table functions
The VALIDATE_DATA, VALIDATE_DATA_FILE, and VALIDATE_DATA_LIBRARY table functions examine the
data in database physical file members to verify it is properly formed. This can be used to identify invalid
data, such as invalid decimal values, that were inserted into a DDS-created physical file.
Authorization: See Note below.

VALIDATE_DATA ( library-name ,
LIBRARY_NAME =>

file-name
FILE_NAME =>

)
, member-name
MEMBER_NAME =>

library-name An character string expression that specifies the name of the library containing file-
name.

416 IBM i: Performance and Query Optimization


file-name A character string expression that specifies the name of a database physical file.
member-name A character string expression that specifies the name of a member in file-name. The
special values *FIRST and *LAST are supported. If this parameter is omitted, *FIRST is
used.

The VALIDATE_DATA_FILE table function validates all members in a physical file. It is identical to
VALIDATE_DATA except it only has library-name and file-name parameters.
The VALIDATE_DATA_LIBRARY table function validates all members in all physical files in a library. It is
identical to VALIDATE_DATA except it only has a library-name parameter.
The result of the function is a table containing a row for each row in a member that has invalid data in at
least one column. The columns of the result table are described in the following table. The result columns
are nullable.
Table 83. VALIDATE_DATA, VALIDATE_DATA_FILE, and VALIDATE_DATA_LIBRARY table function

Column Name Data Type Description

VALIDATE_TIME TIMESTAMP The timestamp when this row was generated.

LIBRARY_NAME VARCHAR(10) The library containing the file.

FILE_NAME VARCHAR(10) The physical file containing the member.

MEMBER_NAME VARCHAR(10) The member with the invalid data.

RELATIVE_RECORD_NUMBER BIGINT The relative record number (RRN) of the row in MEMBER_NAME with the
invalid data.

SQL_WARNING INTEGER The SQLCODE of the warning that indicated this error.

REASON_CODE INTEGER The reason code from the warning that indicated this error.

COLUMN_NAME VARCHAR(128) The name of the column with the invalid data.

WARNING_TEXT VARCHAR(1000) The text from the warning that indicated this error.

Note
This function is provided in the SYSTOOLS schema as an example of how to examine all the rows in a table
by using an SQL table function. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source
can be extracted and used as a model for building similar functions, or to create a customized version
within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
• Validate the content of all members in FILE1. If no rows are returned, all the data appears to be good.

SELECT * FROM TABLE(SYSTOOLS.VALIDATE_DATA_FILE('APPLIB', 'FILE1'));

IBM i Services
There are many system services that can be accessed through system-provided SQL views, procedures,
and functions. These provide an SQL interface to access, transform, order, and subset the information
without needing to code to a system API.
Information about the supported IBM i releases, including the database PTF groups where each service
was introduced or enhanced, is available in the IBM i Technology Updates wiki. See this page for all the
details: https://www.ibm.com/support/pages/node/1119123

Database performance and query optimization 417


Application Services
These procedures, functions, and views provide interface information that can be used by applications.

ACTIVATION_GROUP_INFO table function


The ACTIVATION_GROUP_INFO table function returns all the activation groups that are associated with a
job and their attributes.
This information is similar to what can be accessed through the Display Job (DSPJOB) CL command and
the Open List of Activation Group Attributes (QWVOLAGP) API.
Authorization: None required for a job where the caller's user profile is the same as the job user identity
of the job for which the information is being returned.
Otherwise, the caller must have *JOBCTL special authority.

ACTIVATION_GROUP_INFO (
job-name
JOB_NAME =>

, internal-job-id
INTERNAL_JOB_ID =>

)
, ignore-errors
IGNORE_ERRORS =>

The schema is QSYS2.

job-name A character string that identifies the qualified name of a job in the form job-number/
job-user/job-name.
The special value of '*' indicates the current job.
If job-name is provided, internal-job-id must be omitted.
internal-job- A binary string that contains an internal job identifier. This can be passed for
id quicker performance. This value is returned in the INTERNAL_JOB_ID column by the
ACTIVE_JOB_INFO table function.
If internal-job-id is provided, job-name must be omitted.
ignore-errors A character string that identifies what to do when an error is encountered.

NO An error is returned.
YES A warning is returned.
No row is returned when an error is encountered. This is the default.

The result of the function is a table containing one row for every activation group for the job with the
format shown in the following table. All columns are nullable.
Table 84. ACTIVATION_GROUP_INFO table function

Column Name Data Type Description

ACTIVATION_GROUP_NAME VARCHAR(10) The name of the activation group. Can contain one of the following
special values:

*DFTACTGRP The activation group is one of the default


activation groups.

*NEW The activation group is *NEW.

418 IBM i: Performance and Query Optimization


Table 84. ACTIVATION_GROUP_INFO table function (continued)

Column Name Data Type Description

ACTIVATION_GROUP_NUMBER DECIMAL(20,0) The activation group number.

STORAGE_MODEL VARCHAR(10) The storage model of the activation group.

*SNGLVL The activation group is single level store.

*TERASPACE The activation group is teraspace.

STATE VARCHAR(6) The state of the activation group.

SYSTEM The activation group is in system state.

USER The activation group is in user state.

NUMBER_OF_ACTIVATIONS INTEGER The total number of program activations in this activation group.

PROGRAM_LIBRARY VARCHAR(10) The name of the library that contains the program that caused this
activation group to be created.
Contains the null value when PROGRAM is null.

PROGRAM VARCHAR(10) The name of the program that caused this activation group to be
created.
Contains the null value when the activation group is one of the
default activation groups or if the program no longer exists in the
system.

PROGRAM_TYPE VARCHAR(6) The type of program that caused this activation group to be
created.

JAVA A Java program.

PGM A program.

SRVPGM A service program.

Contains the null value when PROGRAM is null.

SHARED_ACTIVATION_GROUP VARCHAR(3) Whether the activation group is shared. A shared activation group
is an activation group that belongs to more than one job at the
same time.

NO The activation group is not shared with other jobs.

YES The activation group is shared with other jobs.

IN_USE VARCHAR(3) Whether the activation group is eligible to be reclaimed. An


activation group can be reclaimed using the Reclaim Activation
Group (RCLACTGRP) command.

NO The activation group is not in use and is eligible to be


reclaimed.

YES The activation group is in use and cannot be reclaimed.

STATIC_STORAGE_SIZE DECIMAL(20,0) The total amount of static storage allocated to the activation group,
in bytes. If the size exceeds 4,294,967,295 bytes, 4,294,967,295
will be returned.

NUMBER_OF_HEAPS INTEGER The total number of heaps that are allocated by this activation
group.

HEAP_STORAGE_SIZE DECIMAL(20,0) The total amount of heap storage that is allocated to the
activation group, in bytes. If the size exceeds 4,294,967,295
bytes, 4,294,967,295 will be returned.

Example
• List the activation group information for the current job.

SELECT * FROM TABLE(QSYS2.ACTIVATION_GROUP_INFO('*'));

• List the activation group information for a job based on its internal job identifier.

Database performance and query optimization 419


SELECT * FROM TABLE(QSYS2.ACTIVATION_GROUP_INFO(
INTERNAL_JOB_ID => BX'00D10003007E3F00A784A7CBD6E89001'));

ADD_USER_INDEX_ENTRY and ADD_USER_INDEX_ENTRY_BINARY


procedures
The ADD_USER_INDEX_ENTRY and ADD_USER_INDEX_ENTRY_BINARY procedures add a single entry to
a user index (*USRIDX). The data to be added can be provided as either character or binary data.
For a fixed length index, the length of the new entry must exactly match the user index length or an error
will occur.
The values used by the procedures are closely related to the values handled by the Add User Index
Entries (QUSADDUI) API. Refer to the API documentation for additional behavior details.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the user index, and
• *CHANGE authority to the user index.

ADD_USER_INDEX_ENTRY ( user-index

ADD_USER_INDEX_ENTRY_BINARY USER_INDEX =>

, user-index-library
USER_INDEX_LIBRARY =>

, replace , entry
REPLACE => ENTRY =>

)
, key
KEY =>

The schema is QSYS2.

user- A character string containing the name of the user index where an entry is to be added.
index
user- A character string containing the name of the library where the user index is located. Can be
index- one of the following special values:
library
*CURLIB The current library is used.
*LIBL The library list is used.

replace The type of add to be performed.

NO For a non-keyed index, the new entry must be unique. If the entry is already in the
index, an error is returned.
For a keyed index, insert the entry only if the key is not already in the user index. If the
entry does not exist, the key and entry data will be inserted into the user index. If the
entry is already in the index, an error is returned.
YES For a non-keyed index, this value is not supported.
For a keyed index, replace the entry portion of the index entry if the key is already in
the user index. If the entry does not exist, the key and entry data will be inserted into
the user index.

entry A string that specifies the data for the index entry. This parameter is required.

420 IBM i: Performance and Query Optimization


• For ADD_USER_INDEX_ENTRY, the input value is a character string.
• For ADD_USER_INDEX_ENTRY_BINARY, the input value will be considered a binary string.

key A string that specifies the key for the index entry. This parameter must be provided for a
keyed user index. The length of the key cannot exceed the defined key length.
• For ADD_USER_INDEX_ENTRY, the input value is a character string.
• For ADD_USER_INDEX_ENTRY_BINARY, the input value will be considered a binary string.
If the index is not keyed, this parameter must be omitted.

Example
• Add a new entry to a non-keyed user index.

CALL QSYS2.ADD_USER_INDEX_ENTRY(USER_INDEX => 'IX1',


USER_INDEX_LIBRARY => 'APPLIB',
REPLACE => 'NO',
ENTRY => 'Next entry');

• Add a new entry to a keyed user index. Allow the new entry to overwrite an existing entry if the key
value already exists.

CALL QSYS2.ADD_USER_INDEX_ENTRY(USER_INDEX => 'USRIX1',


USER_INDEX_LIBRARY => 'APPLIB',
REPLACE => 'YES',
KEY => '00173',
ENTRY => 'New keyed entry');

BINDING_DIRECTORY_INFO view
The BINDING_DIRECTORY_INFO view returns information about the object entries in binding directories.
The values returned for the columns in the view are similar to the values returned by the Display Binding
Directory (DSPBNDDIR) CL command
Authorization: The caller must have:
• *USE authority to the library containing the binding directory, and
• *OBJOPR and *READ authority to the binding directory.
To return the create timestamp for a binding directory entry, the caller must have:
• *EXECUTE authority to the library containing the binding directory entry, and
• Some authority to the binding directory entry.
The following table describes the columns in the view. The system name is BNDDIR_INF. The schema is
QSYS2.
Table 85. BINDING_DIRECTORY_INFO view

Column Name System Column Name Data Type Description

BINDING_DIRECTORY_LIBRARY BNDDIR_LIB VARCHAR(10) The library containing the binding directory.

BINDING_DIRECTORY BNDDIR VARCHAR(10) The binding directory name.

ENTRY_LIBRARY ENTRY_LIB VARCHAR(10) The library containing ENTRY. Can contain the special value
*LIBL.

ENTRY ENTRY VARCHAR(10) The name of the binding directory entry.

ENTRY_TYPE ENTRY_TYPE VARCHAR(7) The object type of the binding directory entry.

*MODULE The object is a module.

*SRVPGM The object is a service program.

Database performance and query optimization 421


Table 85. BINDING_DIRECTORY_INFO view (continued)

Column Name System Column Name Data Type Description

ENTRY_ACTIVATION ENTRY_ACT VARCHAR(6) The activation control of the bound service program.
Nullable
*DEFER Activation of the bound service program may be
deferred until a function it exports is called.

*IMMED Activation of the bound service program takes place


immediately when the program or service program
it is bound to is activated.

Contains the null value if ENTRY_TYPE is *MODULE.

ENTRY_CREATE_TIMESTAMP ENTRY_TS TIMESTAMP(0) The timestamp when the object was created.
Nullable Contains the null value if the entry timestamp is not available.

Examples
• Return a list of the entries for all binding directories in library TESTLIB that start with 'TEST'.

SELECT * FROM QSYS2.BINDING_DIRECTORY_INFO


WHERE BINDING_DIRECTORY_LIBRARY = 'TESTLIB'
AND BINDING_DIRECTORY LIKE 'TEST%'
ORDER BY BINDING_DIRECTORY_LIBRARY,
BINDING_DIRECTORY,
ENTRY_LIBRARY,
ENTRY;

• List all of the binding directories that have the entry MYLIB/HELLO, type *MODULE.

SELECT BINDING_DIRECTORY,
BINDING_DIRECTORY_LIBRARY
FROM QSYS2.BINDING_DIRECTORY_INFO
WHERE ENTRY = 'HELLO'
AND ENTRY_LIBRARY = 'MYLIB'
AND ENTRY_TYPE = '*MODULE'
ORDER BY 1, 2;

BOUND_MODULE_INFO view
The BOUND_MODULE_INFO view returns information about modules bound into an ILE program or
service program.
The values returned for the columns in the view are closely related to the values returned for *MODULE
detail on the DSPPGM (Display Program) and DSPSRVPGM (Display Service Program) CL commands and
the List ILE Program Information (QBNLPGMI) and the List Service Program Information (QBNLSPGM)
APIs.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the program or service program, and
• *READ authority to the program or service program.
The following table describes the columns in the view. The system name is MODULE_INF. The schema is
QSYS2.
Table 86. BOUND_MODULE_INFO view

Column Name System Column Name Data Type Description

PROGRAM_LIBRARY PGM_LIB VARCHAR(10) The library containing the program or service


program.

PROGRAM_NAME PGM_NAME VARCHAR(10) The program or service program containing the


module.

422 IBM i: Performance and Query Optimization


Table 86. BOUND_MODULE_INFO view (continued)

Column Name System Column Name Data Type Description

OBJECT_TYPE OBJ_TYPE VARCHAR(7) Object type for PROGRAM_NAME.

*PGM A program.

*SRVPGM A service program.

BOUND_MODULE_LIBRARY BDMODLIB VARCHAR(10) The library containing the module bound into
PROGRAM_NAME at bind time.

BOUND_MODULE BDMOD VARCHAR(10) The module bound into PROGRAM_NAME. This


is a copy of the module that was bound into
PROGRAM_NAME. It is not the *MODULE object
on the system.

MODULE_ATTRIBUTE ATTRIBUTE VARCHAR(10) The language in which the module is written.

Nullable Can contain the null value, for example, for a


module created by a compilation process internal
to IBM.

MODULE_CREATE_TIMESTAMP CREATE_TS TIMESTAMP(0) The timestamp when the module was created.

Nullable Contains the null value if no timestamp is


available.

SOURCE_FILE_LIBRARY SRCLIB VARCHAR(10) The name of the library that contains the source
file used to create the module.
Nullable
Contains the null value if no source file was used
to create the module.

SOURCE_FILE SRCFILE VARCHAR(10) The name of the source file used to create the
module.
Nullable
Contains the null value if no source file was used
to create the module.

SOURCE_FILE_MEMBER SRCMBR VARCHAR(10) The name of the member in the source file.

Nullable Contains the null value if no source file was used


to create the module.

SOURCE_STREAM_FILE_PATH SRCSTMF VARGRAPHIC(5000) The absolute path to the source stream


CCSID 1200 file that was used to create this
module. If the stream file is contained
Nullable the /QSYS.LIB file system, will contain the
path to the stream file (e.g., /QSYS.LIB/
library.LIB/filename.FILE/member.MBR) and the
SOURCE_FILE, SOURCE_FILE_LIBRARY, and
SOURCE_FILE_MEMBER will contain the
database equivalent name.
Contains the null value if no source file was used
to create the module.

SOURCE_CHANGE_ SRC_CHGTS TIMESTAMP(0) The timestamp when the source that was used to
TIMESTAMP create this module was last changed.
Nullable
Contains the null value if no source file was used
to create the module.

MODULE_CCSID TGTCCSID INTEGER The coded character set identifier (CCSID) for this
module.

SORT_SEQUENCE_LIBRARY SRTSEQ_LIB VARCHAR(10) The name of the library that contained the sort
sequence table used when the module was
Nullable compiled. This does not apply to SQL statements
in the module. Can contain the following special
values:

*LIBL The sort sequence table is


found in the library list when
PROGRAM_NAME runs this module.

*CURLIB The sort sequence table is found


in the current library when
PROGRAM_NAME runs this module.

Contains the null value if SORT_SEQUENCE


contains a special value or is null.

Database performance and query optimization 423


Table 86. BOUND_MODULE_INFO view (continued)

Column Name System Column Name Data Type Description

SORT_SEQUENCE SRTSEQ VARCHAR(10) The name of the sort sequence table used when
the module was compiled. This does not apply to
Nullable SQL statements in the module. Can contain the
following special values:

*HEX No sort sequence is used.

*JOBRUN The sort sequence value


associated with the job at the
time PROGRAM_NAME runs
this module is used.

*LANGIDSHR The shared sort sequence for


the language identifier is used.

*LANGIDUNQ The unique sort sequence for


the language identifier is used.

Contains the null value if the module does not


contain any sort sequence information.

LANGUAGE_ID LANGID VARCHAR(7) The language identifier used when the module
was compiled. This does not apply to SQL
Nullable statements in the module. Can contain the
following special value:

*JOBRUN The language identifier associated


with the job at the time
PROGRAM_NAME runs this module.

Contains the null value if the module does not


contain any language identification information.

DEBUG_DATA DEBUG_DATA VARCHAR(4) Whether debug data was generated when this
module was created. If debug data exists, the
module may be debugged using the source
debugger.

*NO Debug data was not generated.

*YES Debug data was generated.

OPTIMIZATION_LEVEL OPTIMIZE INTEGER Optimization level for the module. Optimization


improves the performance of a module, but
reduces the ability to immediately change and
accurately display the value of variables during
debugging.

10 No additional optimization is performed


on the generated code. Variables can be
displayed and changed when the program
is being debugged. With no optimization of
the code, this value provides the lowest
level of module performance. 10 is also
known as *NONE.

20 Some optimization is performed on


the generated code. When the module
optimized at this level is being debugged,
the variables can be displayed but not
changed. 20 is also known as *BASIC.

30 More optimization is performed in addition


to those performed at optimization level
20. Variables cannot be changed but can
be displayed while the program is being
debugged. However, the displayed value of
the variable during debugging may not be
its actual value. 30 is also known as *FULL.

40 Maximum level of optimization. This level


includes all the optimizations performed
at optimization level 30. In addition, it
includes optimization that disables call
and instruction tracing. Thus, tracing of
modules created at this optimization level
cannot be done.

424 IBM i: Performance and Query Optimization


Table 86. BOUND_MODULE_INFO view (continued)

Column Name System Column Name Data Type Description

MAX_OPTIMIZATION_LEVEL MAX_OPTLVL INTEGER The highest level of optimization this module


could have at bind time. If observability has
Nullable been removed from the module, this maximum
optimization level value might not be the same as
the one specified at module creation.
The values are identical to the values for the
OPTIMIZATION_LEVEL column.
Contains the null value if the module is not
restricted to a maximum optimization level.
The module can be retranslated to any of the
supported optimization levels.

OBJECT_CONTROL_LEVEL OBJSSI CHAR(8) The object control level for the module at the time
it was bound into PROGRAM_NAME.
Nullable
Contains the null value if there is no object control
level for the module.

RELEASE_CREATED_ON CREATE_ON CHAR(6) The version, release, and modification level of


the operating system on which the module was
created, in VxRxMx format.

TARGET_RELEASE TGTRLS CHAR(6) The version, release, and modification level of


the operating system for which the module was
created, in VxRxMx format.

CREATION_DATA CREATEDATA VARCHAR(6) Whether the bound module has all the
creation data and if that data is observable or
unobservable.

*NO Not all the creation data is present in


the bound module.

*UNOBS The creation data is present in the


bound module but not all of that data
is observable.

*YES The creation data is present in the


bound module and all of that data is
observable.

TERASPACE_STORAGE_ENABLED TERASPACE VARCHAR(4) The teraspace storage capability for this bound
module.

*NO The module is not teraspace storage


enabled.

*YES The module is teraspace storage


enabled.

STORAGE_MODEL STGMDL VARCHAR(10) Where the automatic and static storage for this
bound module is allocated at run time.

*INHERIT Automatic and static storage


are allocated from either single-
level storage or teraspace,
depending on the activation.

*SNGLVL Automatic and static storage


are allocated from single-level
storage.

*TERASPACE Automatic and static storage


are allocated from teraspace.

NUMBER_PROCEDURES PROCS INTEGER The number of procedures defined in the


module. This number includes the program entry
procedure (PEP), if one was generated by the
compiler for this module.

NUMBER_PROCEDURES_BLOCK_ PROCS_BRO INTEGER The number of procedures defined in the module


REORDERED that are block reordered.
If the module does not have block-order profiling
data applied, this value will be zero.

Database performance and query optimization 425


Table 86. BOUND_MODULE_INFO view (continued)

Column Name System Column Name Data Type Description

NUMBER_PROCEDURES_BLOCK_ PROCS_BOM INTEGER The number of procedures defined in the module


ORDER_MEASURED that had block-order profiling data collected at
the time block-order profiling data was applied.
If the module does not have block-order profiling
data applied, this value will be zero.

PROFILING_DATA PRFDTA VARCHAR(10) The profiling data attribute for this bound module.

*APYBLKORD Block-order profiling data


is applied to the module.
See NUMBER_PROCEDURES_
BLOCK_REORDERED for the
current number of procedures
in this module that are block
reordered.

*COL The collection of profiling


data is enabled. Any block-
order profiling data has been
removed for the module.

*NOCOL The collection of profiling data


is not enabled and block-order
profiling data is not applied to
the module.

ALLOW_RTVCLSRC RTVCLSRC VARCHAR(4) Whether the module has CL source data that can
be retrieved from the program.

*NO There is no CL source for this module.

*YES There is CL source for this module.

USER_MODIFIED USER_MOD VARCHAR(4) Indicates whether the module was changed by


the user at bind time.
Nullable
*NO The user did not change the module.

*YES The user changed the module.

Contains the null value if the information is not


available.

LIC_OPTIONS LICOPT VARGRAPHIC(500) CCSID The Licensed Internal Code options that are in
1200 use by the module.

Nullable Contains the null value if no LIC options were


used for the module.

LICENSED_PROGRAM LICPGM VARCHAR(13) If the module was part of a licensed program at


bind time, contains the product number and the
Nullable level of the licensed program.
Contains the null value if the module was not part
of a licensed program at bind time.

PTF_NUMBER PTF CHAR(5) The program temporary fix (PTF) that resulted in
the creation of the module.
Nullable
Contains the null value for user-created modules.

APAR_ID APAR_ID CHAR(6) The module was changed as the result of the
authorized program analysis report (APAR) with
Nullable this identification number.
Contains the null value if the module was not
changed at bind time.

SQL_STATEMENT_COUNT NBRSTMTS INTEGER The number of SQL statements contained in the


module.
Contains 0 if there are no SQL statements in the
module.

426 IBM i: Performance and Query Optimization


Table 86. BOUND_MODULE_INFO view (continued)

Column Name System Column Name Data Type Description

SQL_RELATIONAL_DATABASE RDB VARCHAR(18) The default relational database that was specified
on the SQL precompile. Can contain the following
Nullable special value:

*LOCAL The module can only access data on


the local system.

Contains the null value if no package was created


for the module by the SQL precompiler or if the
module does not contain SQL statements.

SQL_COMMITMENT_CONTROL ISOLATION VARCHAR(5) The level of commitment control that was


specified on the SQL precompile.
Nullable
*ALL Read stability.

*CHG Uncommitted read.

*CS Cursor stability.

*NONE No commit.

*RR Repeatable read.

Contains the null value if the module does not


contain SQL statements.

SQL_NAMING NAMING VARCHAR(4) The convention used for naming objects in SQL
statements.
Nullable
*SQL The SQL naming convention is used.

*SYS The system naming convention is used.

Contains the null value if the module does not


contain SQL statements.

SQL_DATE_FORMAT DATFMT VARCHAR(4) The date format attribute.

Nullable *DMY Day/month/year format (dd/mm/yy).

*EUR European format (dd.mm.yyyy).

*ISO International Standards Organization


format (yyyy-mm-dd).

*JIS Japanese Industrial Standard format


(yyyy-mm-dd).

*JUL Julian format (yy/dds).

*MDY Month/day/year format (mm/dd/yy).

*USA USA format (mm/dd/yyyy).

*YMD Year/month/day format (yy/mm/dd).

Contains the null value if the module does not


contain SQL statements.

SQL_DATE_SEPARATOR DATSEP CHAR(1) The date separator attribute.

Nullable Contains the null value if the module does not


contain SQL statements.

SQL_TIME_FORMAT TIMFMT VARCHAR(4) The time format attribute.

Nullable *EUR European format (hh.mm.ss).

*HMS Hours/minutes/seconds format


(hh:mm:ss).

*ISO International Standards Organization


format (hh.mm.ss).

*JIS Japanese Industrial Standard format


(hh.mm.ss).

*USA USA format (hh:mm a.m. or p.m.).

Contains the null value if the module does not


contain SQL statements.

Database performance and query optimization 427


Table 86. BOUND_MODULE_INFO view (continued)

Column Name System Column Name Data Type Description

SQL_TIME_SEPARATOR TIMSEP CHAR(1) The time separator attribute.

Nullable Contains the null value if the module does not


contain SQL statements.

SQL_SORT_SEQUENCE_LIBRARY SQL_SSEQLB VARCHAR(10) The name of the library that is used to locate the
SQL sort sequence table. The following special
Nullable values can be returned:

*CURLIB The SQL sort sequence table is


found by looking in the current
library.

*LIBL The SQL sort sequence table is


found by looking in the library list.

Contains the null value if SQL_SORT_SEQUENCE


contains a special value or if the module does not
contain SQL statements.

SQL_SORT_SEQUENCE SQL_SRTSEQ VARCHAR(10) The sort sequence table name specified when
the module was compiled. The following special
Nullable values can be returned:

*HEX No SQL sort sequence is used


for the SQL statements.

*JOBRUN The SQL sort sequence is the


SRTSEQ value associated with
the job at the time the SQL
statements within the module
are run.

*LANGIDSHR The shared SQL sort sequence


for the language identifier
(LANGID) is used for the SQL
statements.

*LANGIDUNQ The unique SQL sort sequence


for the language identifier
(LANGID) is used for the SQL
statements.

Contains the null value if the module does not


contain SQL statements.

SQL_LANGUAGE_ID SQL_LANGID VARCHAR(7) The language identifier specified when the


module was compiled. The following special value
Nullable can be returned:

*JOBRUN The language identifier is the


LANGID associated with the job at
the time the module is run.

Contains the null value if the module does not


contain SQL statements.

SQL_DEFAULT_SCHEMA DFTRDBCOL VARCHAR(10) The schema name used for unqualified names of
tables, views, indexes, and SQL packages in static
Nullable statements.
Contains the null value if there is no default
schema name or if the module does not contain
SQL statements.

SQL_PATH SQLPATH VARCHAR(3483) The list of libraries used during resolution of


functions, procedures, and data types within SQL
Nullable statements. The list is in the form of repeating
library names, each surrounded by double quotes
and separated by commas.
Contains the null value if the module does not
contain SQL statements.

428 IBM i: Performance and Query Optimization


Table 86. BOUND_MODULE_INFO view (continued)

Column Name System Column Name Data Type Description

SQL_DYNAMIC_USER_PROFILE DYNUSRPRF VARCHAR(10) The user profile used for dynamic SQL
statements. The following special values can be
Nullable returned:

*OWNER Local dynamic SQL statements


are run under the profile of the
program or service program's owner.
Distributed dynamic SQL statements
are run under the profile of the SQL
package's owner.

*USER Local dynamic SQL statements are


run under the profile of the job
or thread. Distributed dynamic SQL
statements are run under the profile
of the application server job.

Contains the null value if the module does not


contain SQL statements.

SQL_ALLOW_COPY_DATA ALWCPYDTA VARCHAR(9) Whether a copy of the data can be used in the
implementation of an SQL query.
Nullable
*NO A copy of the data is not allowed.

*OPTIMIZE A copy of the data is allowed


whenever it might result is better
performance.

*YES A copy of the data is allowed, but


only when necessary.

Contains the null value if the module does not


contain SQL statements.

SQL_CLOSE_SQL_CURSOR CLOSQLCSR VARCHAR(10) Specifies the CLOSQLCSR attribute.

Nullable *ENDACTGRP SQL cursors are closed,


SQL prepared statements are
implicitly discarded, and LOCK
TABLE locks are released when
the activation group ends.

*ENDMOD SQL cursors are closed and


SQL prepared statements are
implicitly discarded when the
module is exited. LOCK TABLE
locks are released when the
first SQL program on the call
stack ends.

Contains the null value if the module does not


contain SQL statements.

SQL_DELAY_PREPARE DLYPRP VARCHAR(4) Indicates the delay prepare attribute.

Nullable *NO Dynamic statement validation is


performed when the dynamic
statements are prepared.

*YES Dynamic statement validation is delayed


until the dynamic statements are used.

Contains the null value if the module does not


contain SQL statements.

Database performance and query optimization 429


Table 86. BOUND_MODULE_INFO view (continued)

Column Name System Column Name Data Type Description

SQL_ALLOW_BLOCK ALWBLK VARCHAR(8) Whether blocking is used to improve the


performance of certain SQL statements.
Nullable
*ALLREAD Rows are blocked for read-only
cursors.

*NONE Rows are not blocked for retrieval


of data for cursors.

*READ Rows are blocked for read-only


retrieval of data for cursors when:
• The commitment control value
is *NONE.
• The cursor is declared with a
FOR READ ONLY clause or there
are no dynamic statements that
could run a positioned UPDATE
or DELETE statement for the
cursor.

Contains the null value if the module does not


contain SQL statements.

SQL_PACKAGE_LIBRARY SQLPKGLIB VARCHAR(10) The name of the library the SQL package is in.

Nullable Contains the null value if the module is not


distributed or if the module does not contain SQL
statements.

SQL_PACKAGE SQLPKG VARCHAR(10) The name of the SQL package created on


the relational database specified on the RDB
Nullable parameter of the command that created this
module.
Contains the null value if the module is not
distributed or if it does not contain SQL
statements.

SQL_RDB_CONNECTION_METHOD RDBCNNMTH VARCHAR(4) Specifies the semantics used for CONNECT


statements:
Nullable
*DUW CONNECT (Type 2) semantics are used
to support distributed unit of work.

*RUW CONNECT (Type 1) semantics are used


to support remote unit of work.

Contains the null value if the module is not


distributed or does not contain SQL statements.

Examples
• Find any bound modules that include source changes from the last 7 days.

SELECT *
FROM QSYS2.BOUND_MODULE_INFO
WHERE PROGRAM_LIBRARY = 'QGPL'
AND SOURCE_CHANGE_TIMESTAMP > CURRENT TIMESTAMP - 7 DAYS
ORDER BY SOURCE_CHANGE_TIMESTAMP DESC;

• Find bound modules in APPLIB that were built from source that does not reside in the IFS.

SELECT *
FROM QSYS2.BOUND_MODULE_INFO
WHERE PROGRAM_LIBRARY = 'APPLIB'
AND SOURCE_FILE_LIBRARY <> 'QTEMP'
AND SOURCE_STREAM_FILE_PATH IS NULL
ORDER BY SOURCE_FILE_LIBRARY, SOURCE_FILE, SOURCE_FILE_MEMBER;

430 IBM i: Performance and Query Optimization


BOUND_SRVPGM_INFO view
The BOUND_SRVPGM_INFO view returns information about service programs bound into an ILE program
or service program.
The values returned for the columns in the view are closely related to the values returned for *SRVPGM
detail on the DSPPGM (Display Program) and DSPSRVPGM (Display Service Program) CL commands and
the List ILE Program Information (QBNLPGMI) and the List Service Program Information (QBNLSPGM)
APIs.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the program or service program, and
• *READ authority to the program or service program.
The following table describes the columns in the view. The system name is SRVPGM_INF. The schema is
QSYS2.
Table 87. BOUND_SRVPGM_INFO view

Column Name System Column Name Data Type Description

PROGRAM_LIBRARY PGM_LIB VARCHAR(10) Library containing the program or service


program.

PROGRAM_NAME PGM_NAME VARCHAR(10) Program or service program name.

OBJECT_TYPE OBJ_TYPE VARCHAR(7) Object type for PROGRAM_NAME.

*PGM A program.

*SRVPGM A service program.

BOUND_SERVICE_PROGRAM_LIBRARY BDSRVPGMLB VARCHAR(10) The name of the library containing the service
program bound to PROGRAM_NAME at bind time.
This is the library name in which the activation
expects to find the service program at run time.
Can contain the following special value:

*LIBL Indicates the library list is used at the


time the service program is needed.

BOUND_SERVICE_PROGRAM BDSRVPGM VARCHAR(10) The name of the service program bound to


PROGRAM_NAME.

BOUND_SERVICE_PROGRAM_SIGNATURE SIGNATURE BINARY(16) The current signature of the service program


at the time the service program was bound to
PROGRAM_NAME.

BOUND_SERVICE_PROGRAM_ACTIVATION SRVPGM_ACT VARCHAR(6) Specifies when the bound service program is


activated.

*DEFER The bound service program


activation is deferred until a
procedure it exports is called.

*IMMED The bound service program


activation happens when
PROGRAM_NAME is activated.

Example
• Examine whether service programs in APPLIB are taking advantage of deferred service program
activation.

SELECT BOUND_SERVICE_PROGRAM_ACTIVATION, COUNT(*) AS BOUND_SERVICE_PROGRAM_ACTIVATION_COUNT


FROM QSYS2.BOUND_SRVPGM_INFO
WHERE PROGRAM_LIBRARY = 'APPLIB'
GROUP BY BOUND_SERVICE_PROGRAM_ACTIVATION
ORDER BY 2 DESC;

Database performance and query optimization 431


CHANGE_USER_SPACE and CHANGE_USER_SPACE_BINARY procedures
The CHANGE_USER_SPACE and CHANGE_USER_SPACE_BINARY procedures change the contents of a
user space (*USRSPC) object by writing a specified amount of data to the object at a specified location.
The data can be provided as either character or binary data.
The values used by the procedures are closely related to the values handled by the Change User Space
(QUSCHGUS) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the user space, and
• *CHANGE authority to the user space.

CHANGE_USER_SPACE ( user-space

CHANGE_USER_SPACE_BINARY USER_SPACE =>

, user-space-library
USER_SPACE_LIBRARY =>

, data
DATA =>

, start-position
START_POSITION =>

)
, force
FORCE =>

The schema is QSYS2.

user-space A character string containing the name of the user space to be changed.
user- A character string containing the name of the library containing the user space to be
space- changed. Can be one of the following special values:
library
*CURLIB The job's current library is used.
*LIBL The library list is used.

data The data to be written to the user space. The string can be up to 16,773,120 bytes long.
• For CHANGE_USER_SPACE, the input value will be converted to a character string using
the job CCSID.
• For CHANGE_USER_SPACE_BINARY, the input value will be considered a binary string.

start- An integer value that indicates the position in the user space where data will be written.
position The first position in the user space is position 1. If this parameter is omitted, 1 will be used.
force A character string that indicates whether changes made to the user space should be forced
to auxiliary storage.

ASYNC Force changes asynchronously. This interrupts normal system management and
ensures that the user space is written to auxiliary storage.
NO Do not force changes. Normal system management writes the changes to
auxiliary storage. This is the default.

432 IBM i: Performance and Query Optimization


SYNC Force changes synchronously. This interrupts normal system management and
ensures that the user space is written immediately to auxiliary storage.

Example
• Modify the content of user space USRSPC1 in APPLIB, placing the specified string starting at the 500th
byte in the space.

CALL QSYS2.CHANGE_USER_SPACE(USER_SPACE => 'USRSPC1',


USER_SPACE_LIBRARY => 'APPLIB',
DATA => 'Overwrite with this new value',
START_POSITION => 500);

CHANGE_USER_SPACE_ATTRIBUTES procedure
The CHANGE_USER_SPACE_ATTRIBUTES procedure changes the attributes of a user space (*USRSPC)
object.
The values used by the procedure are closely related to the values handled by the Change User Space
Attributes (QUSCUSAT) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the user space, and
• *CHANGE and *OBJMGT authority to the user space.

CHANGE_USER_SPACE_ATTRIBUTES ( user-space
USER_SPACE =>

, user-space-library
USER_SPACE_LIBRARY =>

, size
SIZE =>

, extendable
EXTENDABLE =>

, initial-value
INITIAL_VALUE =>

)
, transfer-size
TRANSFER_SIZE =>

The schema is QSYS2.

user-space A character string containing the name of the user space to be changed.
user-space- A character string containing the name of the library containing the user space to be
library changed. Can be one of the following special values:

*CURLIB The job's current library is used.

Database performance and query optimization 433


*LIBL The library list is used. This is the default.

size An integer value specifying the size, in bytes, of the user space object. This value must
be from 1 byte to 16,773,120 bytes. If the value is smaller than the current size of the
space, the user space is truncated. If it is larger, the space is extended.
If this parameter is omitted, the size is not changed.
extendable An character string that indicates whether the user space can be automatically
extended.

NO The user space is not automatically extendable.


YES The user space is automatically extendable.

If this parameter is omitted, the automatic extend attribute is not changed.


initial-value A one byte binary value containing the initial value to which future extensions of the user
space will be set. The best performance is when this value indicates hexadecimal zeros
(BX'00').
If this parameter is omitted, the initial value is not changed.
transfer-size An integer value that indicates the number of pages to be transferred between main
storage and auxiliary storage. This is only a request, as system processing can use a
value of its choice in some circumstances. Allowable values are from 0 to 32 pages. A
value of 0 indicates that the default transfer size for the user space should be used. A
larger transfer size may allow for better performance of applications processing the user
space.
If this parameter is omitted, the transfer size is not changed.

Example
• Truncate user space USRSPC1 in APPLIB to a size of 200 bytes.

CALL QSYS2.CHANGE_USER_SPACE_ATTRIBUTES(USER_SPACE => 'USRSPC1',


USER_SPACE_LIBRARY => 'APPLIB',
SIZE => 200);

CLEAR_DATA_QUEUE procedure
The CLEAR_DATA_QUEUE procedure clears all messages from the specified data queue or clears
messages that match the key provided.
This procedure provides function similar to the Clear Data Queue (QCLRDTAQ) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the data queue, and
• *OBJOPR and *READ authority to the data queue.

434 IBM i: Performance and Query Optimization


CLEAR_DATA_QUEUE ( data-queue
DATA_QUEUE =>

, data-queue-library
DATA_QUEUE_LIBRARY =>

, key-data
KEY_DATA =>

)
, key-order
KEY_ORDER =>

The schema is QSYS2.

data- A character or graphic string containing the name of the data queue.
queue
data- A character or graphic string containing the name of the library containing the data queue.
queue- Can be one of the following special values:
library
*CURLIB The job's current library is used.
*LIBL The library list is used. This is the default.

key-data A character string containing the data to use as the key for selecting messages to be
removed from the data queue. This parameter can only be specified for a keyed data queue.
If this parameter is not specified, all messages will be cleared from the data queue.
The length of key-data must be the length specified on the KEYLEN parameter
on the Create Data Queue (CRTDTAQ) command. The KEY_LENGTH column of the
QSYS2.DATA_QUEUE_INFO view contains this value.
When this parameter is specified, key-order must also be specified.
key-order The comparison criteria between the keys of messages on the data queue and the key-data
parameter. Valid values are:

EQ Equal
GE Greater than or equal
GT Greater than
LE Less than or equal
LT Less than
NE Not equal

This parameter is ignored if key-data is not specified.

Example
Clear all entries from data queue DQ1 in library TESTLIB.

CALL QSYS2.CLEAR_DATA_QUEUE('DQ1', 'TESTLIB');

Database performance and query optimization 435


COMMAND_INFO view
The COMMAND_INFO view returns information about all CL commands on the system.
The values returned for the result columns in the view are closely related to the values returned by the
Display Command (DSPCMD) CL command and the Retrieve Command Information (QCDRCMDI) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the command, and
• *USE authority to the command
The following table describes the columns in the view. The system name is CMD_INFO. The schema is
QSYS2.
Table 88. COMMAND_INFO view

Column Name System Column Name Data Type Description

COMMAND_LIBRARY CMD_LIB VARCHAR(10) The name of the library in which the command
resides.

COMMAND_NAME CMD VARCHAR(10) The name of the command about which


information is being returned.

PROXY_COMMAND PROXY_CMD VARCHAR(3) Whether the command is a proxy command.

NO This command is not a proxy command.

YES This command is a proxy command.

PROXY_TARGET_COMMAND_LIBRARY PRXTGT_LIB VARCHAR(10) The name of the library in which the proxy target
command resides. Can contain the special value
Nullable *LIBL.
Contains the null value if PROXY_COMMAND is
NO.

PROXY_TARGET_COMMAND PRXTGT_CMD VARCHAR(10) The name of the proxy target command. This
could be another proxy command.
Nullable
Contains the null value if PROXY_COMMAND is
NO.

TEXT_DESCRIPTION TEXT VARCHAR(50) The text description of the command.

Nullable Contains the null value if there is no text


description.

COMMAND_PROCESSING_PROGRAM_LIBRARY CPP_LIB VARCHAR(10) The name of the library in which the command
processing program resides. Can contain the
Nullable special value *LIBL.
Contains the null value if
COMMAND_PROCESSING_PROGRAM contains
the special value *REXX, or if PROXY_COMMAND
is YES.

COMMAND_PROCESSING_PROGRAM CPP_PGM VARCHAR(10) The name of the program that accepts


parameters from the command and processes
Nullable the command. Can contain the following special
value:

*REXX The command is processed by REXX.

Contains the null value if PROXY_COMMAND is


YES.

COMMAND_PROCESSING_PROGRAM_STATE CPP_STATE VARCHAR(7) The state the command processing program is


called from.
Nullable
*SYSTEM The command processing program
is called from system state.

*USER The command processing program


is called from user state.

Contains the null value if PROXY_COMMAND is


YES.

436 IBM i: Performance and Query Optimization


Table 88. COMMAND_INFO view (continued)

Column Name System Column Name Data Type Description

SOURCE_FILE_LIBRARY SRCLIB VARCHAR(10) The name of the library in which the source file
resides.
Nullable
Contains the null value if a stream file was used
to create the command, or if PROXY_COMMAND is
YES.

SOURCE_FILE SRCFILE VARCHAR(10) The name of the source file that contains the
source file member used to create the command.
Nullable
Contains the null value if a stream file was used
to create the command, or if PROXY_COMMAND is
YES.

SOURCE_FILE_MEMBER SRCMBR VARCHAR(10) The name of the source file member that contains
the command definition statements used to
Nullable create the command.
Contains the null value if a stream file was used
to create the command, or if PROXY_COMMAND is
YES.

VALIDITY_CHECKING_PROGRAM_LIBRARY VLD_LIB VARCHAR(10) The name of the library in which the validity
checking program resides.
Nullable
Contains the null value if
VALIDITY_CHECKING_PROGRAM contains the
null value, or if PROXY_COMMAND is YES.

VALIDITY_CHECKING_PROGRAM VLD_PGM VARCHAR(10) The name of a program that performs additional


user-defined validity checking on the parameters
Nullable in the command.
Contains the null value if no validity checking
program is defined, or if PROXY_COMMAND is
YES.

VALIDITY_CHECKING_PROGRAM_STATE VLD_STATE VARCHAR(7) The state the validity checking program is called
from.
Nullable
*SYSTEM The validity checking program is
called from the system state.

*USER The validity checking program is


called from the user state.

Contains the null value if


VALIDITY_CHECKING_PROGRAM contains the
null value, or if PROXY_COMMAND is YES.

PROMPT_TEXT_MESSAGE_FILE_LIBRARY PMT_LIB VARCHAR(10) The name of the library in which the prompt
message file resides. Can contain the special
Nullable value *LIBL.
Contains the null value if
PROMPT_TEXT_MESSAGE_FILE contains the null
value, or if PROXY_COMMAND is YES.

PROMPT_TEXT_MESSAGE_FILE PMT_MSGF VARCHAR(10) The name of the message file that contains the
prompt text for this command.
Nullable
Contains the null value if no message file was
specified for prompt text, or if PROXY_COMMAND
is YES.

Database performance and query optimization 437


Table 88. COMMAND_INFO view (continued)

Column Name System Column Name Data Type Description

RETRIEVE_PROMPT_MESSAGE RTVPMTMSG VARCHAR(8) Whether text messages used by the command are
retrieved from the prompt message file when the
Nullable command is prompted.

*DYNAMIC When the command is prompted,


the prompt text will be
dynamically retrieved from
PROMPT_TEXT_MESSAGE_FILE.

*STATIC When the command is prompted,


the prompt text will be retrieved
from the static copies of the
messages stored in the *CMD
object when the command was
created.

Contains the null value if no message file was


specified for prompt text, or if PROXY_COMMAND
is YES.

PROMPT_OVERRIDE_PROGRAM_LIBRARY PMTOVR_LIB VARCHAR(10) The name of the library in which the prompt
override program resides.
Nullable
Contains the null value if
PROMPT_OVERRIDE_PROGRAM contains the null
value, or if PROXY_COMMAND is YES.

PROMPT_OVERRIDE_PROGRAM PMTOVR_PGM VARCHAR(10) The name of the prompt override program that
replaces default values (on the prompt display)
Nullable with the current actual values for the parameter.
Contains the null value if no prompt override
program is specified, or if PROXY_COMMAND is
YES.

PROMPT_OVERRIDE_PROGRAM_STATE PMTOVR_ST VARCHAR(7) The state the prompt override program is called
from.
Nullable
*SYSTEM The prompt override program is
called from the system state.

*USER The prompt override program is


called from the user state.

Contains the null value if


PROMPT_OVERRIDE_PROGRAM contains the null
value, or if PROXY_COMMAND is YES.

MESSAGE_FILE_LIBRARY MSGF_LIB VARCHAR(10) The name of the library in which the message file
resides. Can contain the special value *LIBL.
Nullable
Contains the null value if PROXY_COMMAND is
YES.

MESSAGE_FILE MSGF VARCHAR(10) The name of the message file from which
messages identified on the Dependency (DEP)
Nullable command definition statements are retrieved.
Contains the null value if PROXY_COMMAND is
YES.

HELP_PANEL_GROUP_LIBRARY PNLGRP_LIB VARCHAR(10) The name of the library in which the panel group
resides. Can contain the special value *LIBL.
Nullable
Contains the null value if HELP_PANEL_GROUP
contains the null value, or if PROXY_COMMAND
is YES.

HELP_PANEL_GROUP PNLGRP VARCHAR(10) The name of the panel group in which the online
help information exists for this command.
Nullable
Contains the null value if no help panel
group is defined for this command, or if
PROXY_COMMAND is YES.

HELP_IDENTIFIER HELP_ID VARCHAR(10) The root name for all help section identifiers for
this command. All help sections in the help panel
Nullable group associated with this command will begin
with this name.
Contains the null value if no help identifier is
specified, or if PROXY_COMMAND is YES.

438 IBM i: Performance and Query Optimization


Table 88. COMMAND_INFO view (continued)

Column Name System Column Name Data Type Description

HELP_SEARCH_INDEX_LIBRARY HELP_LIB VARCHAR(10) The name of the library in which the help search
index resides. Can contain the special value
Nullable *LIBL.
Contains the null value if HELP_SEARCH_INDEX is
null, or if PROXY_COMMAND is YES.

HELP_SEARCH_INDEX HELP_INDEX VARCHAR(10) The name of the help search index for this
command.
Nullable
Contains the null value if no help search index is
specified, or if PROXY_COMMAND is YES.

CURRENT_LIBRARY_NAME CURLIB VARCHAR(10) The name of the library used as the current
library during the processing of this command.
Nullable Can contain the following special values:

*CRTDFT No current library is active during


processing of the command.

*NOCHG The current library does not change


for the processing of this command.

Contains the null value if PROXY_COMMAND is


YES.

PRODUCT_LIBRARY_NAME PRODLIB VARCHAR(10) The name of the library that is used as the
product library during the processing of the
Nullable command. Can contain the following special
value:

*NOCHG The product library does not change


for the processing of this command.

Contains the null value if there is no product


library used during the processing of the
command, or if PROXY_COMMAND is YES.

MAXIMUM_POSITIONAL_PARAMETERS MAXPOS INTEGER The maximum number of parameters that can be


coded in a positional manner for this command.
Nullable
Contains the null value if no maximum positional
coding limit was specified for the command, or if
PROXY_COMMAND is YES.

ALLOW_LIMITED_USER ALWLMTUSR VARCHAR(3) Whether a user whose profile is set for limited
capabilities is allowed to use the command by
Nullable typing it in the command line on a menu.

NO This command cannot be entered in the


command line on a menu by a user whose
profile is set for limited capabilities.

YES This command can be entered in the


command line on a menu by a user whose
profile is set for limited capabilities.

Contains the null value if PROXY_COMMAND is


YES.

DEBUG_MODE DEBUG_MODE VARCHAR(3) Whether the command is valid for debug mode
operations.
Nullable
NO The command is not valid for debug mode
operations.

YES The command is valid for debug mode


operations.

Contains the null value if PROXY_COMMAND is


YES.

Database performance and query optimization 439


Table 88. COMMAND_INFO view (continued)

Column Name System Column Name Data Type Description

PRODUCTION_MODE PROD_MODE VARCHAR(3) Whether the command is valid for production


mode operations.
Nullable
NO The command is not valid for production
mode operations.

YES The command is valid for production


mode operations.

Contains the null value if PROXY_COMMAND is


YES.

SERVICE_MODE SVC_MODE VARCHAR(3) Whether the command is valid for service mode
operations.
Nullable
NO The command is not valid for service
mode operations.

YES The command is valid for service mode


operations.

Contains the null value if PROXY_COMMAND is


YES.

ALLOW_RUN_INTERACTIVE ALLOWINTER VARCHAR(3) Whether the command can be processed


interactively, external to a CL program.
Nullable
NO The command is not allowed to run in an
interactive job.

YES The command is allowed to run in an


interactive job.

Contains the null value if PROXY_COMMAND is


YES.

ALLOW_RUN_BATCH ALLOWBATCH VARCHAR(3) Whether the command can be processed in a


batch input stream, external to a CL program.
Nullable
NO The command is not allowed to run in a
batch job.

YES The command is allowed to run in a batch


job.

Contains the null value if PROXY_COMMAND is


YES.

ALLOW_RUN_EXEC ALLOWEXEC VARCHAR(3) Whether the command can be used as a


parameter on the CALL command and be
Nullable passed as a character string to the system API
programs QCMDEXC, QCAEXEC, and QCAPCMD
for processing.

NO The command is not allowed to run by


using QCMDEXC, QCAEXEC, or QCAPCMD
API programs.

YES The command is allowed to run by using


QCMDEXC, QCAEXEC, or QCAPCMD API
programs.

Contains the null value if PROXY_COMMAND is


YES.

ALLOW_RUN_BATCH_ENTRY ALLOWBPGM VARCHAR(3) Whether the command can be processed in a CL


program that is called from batch entry.
Nullable
NO The command is not allowed to run in a
batch program.

YES The command is allowed to run in a batch


program.

Contains the null value if PROXY_COMMAND is


YES.

440 IBM i: Performance and Query Optimization


Table 88. COMMAND_INFO view (continued)

Column Name System Column Name Data Type Description

ALLOW_RUN_INTERACTIVE_ENTRY ALLOWIPGM VARCHAR(3) Whether the command can be processed in a CL


program that is called from interactive entry.
Nullable
NO The command is not allowed to run in an
interactive program.

YES The command is allowed to run in an


interactive program.

Contains the null value if PROXY_COMMAND is


YES.

ALLOW_RUN_BATCH_PGM ALLOWBMOD VARCHAR(3) Whether the command can be used in a batch ILE
CL program.
Nullable
NO The command is not allowed to run in a
batch ILE CL program.

YES The command is allowed to run in a batch


ILE CL program.

Contains the null value if PROXY_COMMAND is


YES.

ALLOW_RUN_INTERACTIVE_PGM ALLOWIMOD VARCHAR(3) Whether the command can be used in an


interactive ILE CL program.
Nullable
NO The command is not allowed to run in an
interactive ILE CL program.

YES The command is allowed to run in an


interactive ILE CL program.

Contains the null value if PROXY_COMMAND is


YES.

ALLOW_RUN_BATCH_REXX ALLOWBREXX VARCHAR(3) Whether the command can be used in a REXX


procedure run in a batch job.
Nullable
NO The command is not allowed to run in a
batch REXX job.

YES The command is allowed to run in a batch


REXX job.

Contains the null value if PROXY_COMMAND is


YES.

ALLOW_RUN_INTERACTIVE_REXX ALLOWIREXX VARCHAR(3) Whether the command can be used in a REXX


procedure run in an interactive job.
Nullable
NO The command is not allowed to run in an
interactive REXX job.

YES The command is allowed to run in an


interactive REXX job.

Contains the null value if PROXY_COMMAND is


YES.

CCSID CCSID INTEGER The value of the coded character set identifier
(CCSID) associated with this command. It is the
Nullable value of the job CCSID when this command was
created.
Contains the null value if PROXY_COMMAND is
YES.

Database performance and query optimization 441


Table 88. COMMAND_INFO view (continued)

Column Name System Column Name Data Type Description

GUI_ENABLED GUI_ENB VARCHAR(3) Whether the command prompt panels are


enabled for conversion to a graphical user
Nullable interface.

NO The command prompt panels are not


enabled for conversion to a graphical user
interface.

YES The command prompt panels are enabled


for conversion to a graphical user
interface by including information about
the panel content in the 5250 data
stream.

Contains the null value if PROXY_COMMAND is


YES.

THREADSAFE THREADSAFE VARCHAR(5) Whether the command can be used safely in a


multithreaded job.
Nullable
*COND The command is threadsafe under
certain conditions.

*NO The command is not threadsafe and


should not be used in a multithreaded
job.

*YES The command is threadsafe and can


be used safely in a multithreaded job.

Contains the null value if PROXY_COMMAND is


YES.

MULTITHREADED_JOB_ACTION JOB_ACTION VARCHAR(7) The action to take in a multithreaded job for this
command.
Nullable
*MSG Send an informational message and
run the command.

*NORUN Send an escape message, and do


not run the command.

*RUN Run the command. Do not send a


message.

*SYSVAL Use the action specified in


QMLTTHDACN system value.

Contains the null value if PROXY_COMMAND is


YES.

TARGET_RELEASE TGTRLS CHAR(6) The version, release, and modification level to


which this command is restricted in VxRxMx
Nullable format. This applies only to a command used
in a CL program. It must match the contents of
the target release parameter on the Create CL
Program (CRTCLPGM) command.
Contains the null value if the current release is
used, or if PROXY_COMMAND is YES.

Example
• List all the proxy commands in QSYS.

SELECT *
FROM QSYS2.COMMAND_INFO
WHERE COMMAND_LIBRARY = 'QSYS'
AND PROXY_COMMAND = 'YES';

442 IBM i: Performance and Query Optimization


CREATE_USER_INDEX procedure
The CREATE_USER_INDEX table procedure creates or replaces a user index (*USRIDX) object.
The values used by the procedure are closely related to the values handled by the Create User Index
(QUSCRTUI) API.
Authorization: The caller must have:
• *READ and *ADD authority to the library where the user index is being created.
• If a user index is being replaced, the caller must have *OBJMGT, *OBJEXIST, and *READ authorities to
the existing user index.

Database performance and query optimization 443


CREATE_USER_INDEX ( user-index
USER_INDEX =>

, user-index-library
USER_INDEX_LIBRARY =>

, entry-type
ENTRY_TYPE =>

, maximum-entry-length
MAXIMUM_ENTRY_LENGTH =>

, key-length
KEY_LENGTH =>

, index-size
INDEX_SIZE =>

, replace
REPLACE =>

, index-attribute
INDEX_ATTRIBUTE =>

, optimization
OPTIMIZATION =>

, immediate-update
IMMEDIATE_UPDATE =>

, track-usage
TRACK_USAGE =>

, text-description
TEXT_DESCRIPTION =>

, public-authority
PUBLIC_AUTHORITY =>

)
, object-domain
OBJECT_DOMAIN =>

The schema is QSYS2.

user-index A character string containing the name of the user index to be created.

444 IBM i: Performance and Query Optimization


user-index- A character string containing the name of the library where the user index is to be
library created. Can be the following special value:

*CURLIB The current library is used.

entry-type A character string that indicates the type of entries for the user index.

FIXED Fixed-length entries.


VARIABLE Variable-length entries.

maximum- An integer value that specifies the length of entries in the user index.
entry-length When entry-type is FIXED, valid values are 1 to 2000.
When entry-type is VARIABLE, this parameter is ignored and the value 2000 is used.
key-length An integer value that specifies the length of the key to be used for any insertions into
the user index.
To define a non-keyed index, the value must be 0. This is the default.
To define a keyed index, the value can be 1 to maximum-entry-length.
index-size A character string that indicates the maximum size of the user index.

4 GB The maximum size of the user index is 4 gigabytes. This is the default.
1 TB The maximum size of the user index is 1 terabyte.

replace A character string that indicates whether an existing user index by this name is to be
replaced.

NO Do not replace an existing user index of the same name and library. This is the
default.
YES Replace an existing user index of the same name and library.
If the user index already exists, it is replaced by a new user index with the same
name and library and keeps the original object's authorities.

index-attribute A character string that specifies the user-provided object attribute to assign to the
user index. It can be up to ten characters long. The string will be folded to uppercase.
optimization The optimization method used for user index maintenance.

RANDOM Optimize for random references. This is the default.


SEQUENTIAL Optimize for sequential references.

immediate- Whether the updates to the index are written to auxiliary storage on each update to the
update index.

NO No immediate update. This is the default.


YES Immediate update.

track-usage The usage tracking setting for the user index. Usage tracking provides machine
checkpoints to improve recognition that the index is bad. If a user index is found
to be a state of partial change, it will be marked as damaged.

NO Do not track usage. This is the default.


YES Track usage.

text-description A character string that describes the user index. It can be up to 50 characters long.

Database performance and query optimization 445


public- The authority given to a newly created user index for users who do not have a specific
authority private or group authority to the user index. This option is ignored if replace has a value
of YES and an existing user index is replaced.

*ALL The public authority allows users to perform all operations on


the user index.
authorization-list- The user index is secured by the specified authorization list,
name and its public authority is set to *AUTL.
*CHANGE The public authority provides users read, add, update, and
delete authority for the user index and they can read the object
description.
*EXCLUDE The public authority prevents users from accessing the user
index in any way.
*LIBCRTAUT The public authority is taken from the CRTAUT value for the
library when the object is created. This is the default.
*USE The public authority allows users to read the object description
and contents but they cannot change the user index.

object-domain The domain into which the user space is created. Refer to the API documentation for
more details.

*DEFAULT The system decides into which domain the object should be created. This
is the default.
*SYSTEM Create the user index object into the system domain.
*USER Attempt to create the user index object into the user domain.
If the library you are creating the user index into does not appear in the
QALWUSRDMN system value, the user index cannot be created into the
user domain.

Example
• Create user space USRIX1 in APPLIB to contain variable-length entries. The key is 5 characters long.
Assign *EXCLUDE public authority to the *USRIDX object.

CALL QSYS2.CREATE_USER_INDEX(USER_INDEX => 'USRIX1',


USER_INDEX_LIBRARY => 'APPLIB',
ENTRY_TYPE => 'VARIABLE',
KEY_LENGTH => 5,
PUBLIC_AUTHORITY => '*EXCLUDE');

CREATE_USER_SPACE procedure
The CREATE_USER_SPACE procedure creates or replaces a user space (*USRSPC) object.
The values used by the procedure are closely related to the values handled by the Create User Space
(QUSCRTUS) API.
Authorization: The caller must have:
• *READ and *ADD authority to the library where the user space is being created.
• If a user space is being replaced, the caller must have *OBJMGT, *OBJEXIST, and *READ authorities to
the existing user space.

446 IBM i: Performance and Query Optimization


CREATE_USER_SPACE ( user-space
USER_SPACE =>

, user-space-library
USER_SPACE_LIBRARY =>

, size
SIZE => , replace
REPLACE =>

, text-description
TEXT_DESCRIPTION =>

, public-authority
PUBLIC_AUTHORITY =>

, extendable
EXTENDABLE =>

, initial-value
INITIAL_VALUE =>

, object-attribute
OBJECT_ATTRIBUTE =>

, transfer-size
TRANSFER_SIZE =>

)
, object-domain
OBJECT_DOMAIN =>

The schema is QSYS2.

user-space A character string containing the name of the user space to be created.
user-space- A character string containing the name of the library where the user space is to be
library created. Can be the following special value:

*CURLIB The job's current library is used.

size The initial size of the user space being created. This value must be from 1 byte to
16,773,120 bytes.
The size of the user space that is created could be larger than the specified value.

replace A character string that indicates whether an existing user space by this name is to be
replaced.

Database performance and query optimization 447


NO Do not replace an existing user space of the same name and library. This is the
default.
YES Replace an existing user space of the same name and library.
If the user space already exists, it is replaced by a new user space with the same
name and library and keeps the original object's authorities.

text- A character string that describes the user space. It can be up to 50 characters long.
description
public- The authority given to a newly created user space for users who do not have a specific
authority private or group authority to the user space. This option is ignored if replace has a value
of YES and an existing user space is replaced.

*ALL The public authority allows users to perform all operations on the
user space.
authorization-list- The user space is secured by the specified authorization list, and
name its public authority is set to *AUTL.
*CHANGE The public authority allows users to read the object description
and provides read, add, update, and delete authority to the user
space.
*EXCLUDE The public authority prevents users from accessing the user
space in any way.
*LIBCRTAUT The public authority is taken from the CRTAUT value for the
library when the object is created. This is the default.
*USE The public authority allows users to read the user space.

extendable A character string that indicates whether the user space can be automatically extended.

NO The user space is not automatically extendable. The user space maximum size
matches the initial size.
YES The user space is automatically extendable. The size of the user space
automatically grows as data is written beyond its current size. This is the default.

initial-value The initial value of all bytes in the user space as a binary value. A value of BX'00' will
achieve the best performance. This is the default.
object- A character string that specifies the user-provided object attribute to assign to the user
attribute space. It can be up to ten characters long. The string will be folded to uppercase.
transfer-size An integer value that indicates the number of pages to be transferred between main
storage and auxiliary storage. This is only a request, as system processing can use a
value of its choice in some circumstances. Allowable values are from 0 to 32 pages. A
value of 0 indicates that the default transfer size for the user space should be used. The
default is 0.
A larger transfer size may allow for better performance of applications processing the
user space.
object- The domain into which the user space is created.
domain
*DEFAULT The system decides into which domain the object should be created. This
is the default.
*SYSTEM Create the user space object into the system domain.
*USER Attempt to create the user space object into the user domain.

448 IBM i: Performance and Query Optimization


If the library you are creating the user space into does not appear in the
QALWUSRDMN system value, the user space cannot be created into the
user domain.

Example
• Create user space USRSPC1 in APPLIB with an initial size of 1000 bytes. Assign *EXCLUDE public
authority to the *USRSPC object.

CALL QSYS2.CREATE_USER_SPACE(USER_SPACE => 'USRSPC1',


USER_SPACE_LIBRARY => 'APPLIB',
SIZE => 1000,
PUBLIC_AUTHORITY => '*EXCLUDE');

DATA_AREA_INFO table function


The DATA_AREA_INFO table function returns a row for the specified data area, including a data area in
QTEMP or the *LDA, *PDA, or *GDA data areas.
The values returned are closely related to the values returned by the Retrieve Data Area (RTVDTAARA) CL
command and the Retrieve Data Area (QWCRDTAA) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the data area, and
• *USE authority to the data area.
For a DDM data area, the caller must be able to connect to the remote system.
To return information for the data area on the remote system, the caller must have:
• *EXECUTE authority to the library containing the data area, and
• *USE authority to the data area.

DATA_AREA_INFO ( data-area-name
DATA_AREA_NAME =>

, data-area-library
DATA_AREA_LIBRARY =>

)
, ignore-errors
IGNORE_ERRORS =>

The schema is QSYS2.

data-area- A character or graphic string expression that identifies the data area.
name
Can contain the following special values:

*GDA Group data area.


*LDA Local data area.
*PDA Program initialization parameter data area.

data-area- A character or graphic string expression that identifies the library containing the data area.
library If data-area-library is not specified, *LIBL is used. If data-area-name is one of the special
values, data-area-library is ignored.

Database performance and query optimization 449


Can contain the following special values:

*CURLIB The current library is used.


*LIBL The library list is used.

ignore- A character or graphic string expression that identifies what to do when an error is
errors encountered.

NO An error is returned. This is the default.


YES A warning is returned.
A partial row is returned when an error is encountered. Columns other than the data
area name (and the library name if explicitly specified as an input parameter) will be
null.

The result of the function is a table containing one row with the format shown in the following table. All
the columns are nullable.
Table 89. DATA_AREA_INFO table function

Column Name Data Type Description

DATA_AREA_LIBRARY VARCHAR(10) Library containing the data area.


Contains the null value if this request is for *GDA, *LDA, or *PDA.

DATA_AREA_NAME VARCHAR(10) Name of the data area.

DATA_AREA_TYPE VARCHAR(5) The type of data area.

*CHAR A character data area.

*DEC A decimal data area.

*LGL A logical data area.

LENGTH INTEGER Specifies the length of the data area.


• For a character data area, it is the maximum number of characters.
• For a decimal data area it is the total number of digits, including
decimal positions.
• For a logical data area, it is always 1.

DECIMAL_POSITIONS INTEGER Specifies the number of digits to the right of the decimal point for a
decimal data area.
Contains the null value if not a decimal data area.

DATA_AREA_VALUE VARCHAR(2000) The value currently assigned to the data area.


For a decimal data area, the SQL default decimal point is used. See
Decimal point.

DATA_AREA_BINARY_VALUE VARBINARY(2000) The value currently assigned to the data area as binary data.

Example
• Return the current value of the TESTDATA data area. Use the library list to locate the data area.

SELECT DATA_AREA_VALUE FROM TABLE(QSYS2.DATA_AREA_INFO(


DATA_AREA_NAME => 'TESTDATA',
DATA_AREA_LIBRARY => '*LIBL'));

DATA_AREA_INFO view
The DATA_AREA_INFO view returns the values of data areas.
The values returned for the columns in the view are closely related to the values returned by the Retrieve
Data Area (RTVDTAARA) CL command and the Retrieve Data Area (QWCRDTAA) API.
Authorization: The caller must have:

450 IBM i: Performance and Query Optimization


• *EXECUTE authority to the library containing the data area, and
• *USE authority to the data area.
For a DDM data area, the caller must be able to connect to the remote system.
To return information for the data area on the remote system, the caller must have:
• *EXECUTE authority to the library containing the data area, and
• *USE authority to the data area.
The following table describes the columns in the view. The system name is DTAARA_INF. The schema is
QSYS2.
Table 90. DATA_AREA_INFO view

Column Name System Column Name Data Type Description

DATA_AREA_LIBRARY DTAARA_LIB VARCHAR(10) Library containing the data area.

DATA_AREA_NAME DTAARA VARCHAR(10) Name of the data area.

DATA_AREA_TYPE TYPE VARCHAR(5) The type of data area.

Nullable *CHAR A character data area.

*DEC A decimal data area.

*LGL A logical data area.

Contains the null value if this is a DDM data area


that was unable to access the data.

LENGTH LENGTH INTEGER Specifies the length of the data area.

Nullable • For a character data area, it is the maximum


number of characters.
• For a numeric data area it is the total number
of digits, including decimal positions.
• For a logical data area, it is always 1.
Contains the null value if this is a DDM data area
that was unable to access the data.

DECIMAL_POSITIONS SCALE INTEGER Specifies the number of digits to the right of the
decimal point for a decimal data area.
Nullable
Contains the null value if not a decimal data area
or if this is a DDM data area that was unable to
access the data.

DATA_AREA_VALUE VALUE VARCHAR(2000) The value currently assigned to the data area as
character data.
Nullable
For a decimal data area, the SQL default decimal
point is used. See Decimal point.
Contains the null value if this is a DDM data area
that was unable to access the data.

DATA_AREA_BINARY_VALUE BIN_VALUE VARBINARY(2000) The value currently assigned to the data area as
binary data.
Nullable
Contains the null value if this is a DDM data area
that was unable to access the data.

SQL_SEQUENCE SEQUENCE VARCHAR(3) This data area is defined as an SQL sequence.

NO This is not an SQL sequence.

YES This is an SQL sequence.

TEXT_DESCRIPTION TEXT VARCHAR(50) The text description of the data area.

Nullable Contains the null value if the data area has no


description or if this is a DDM data area.

Example
• Return a list of values for all data areas in MYLIB.

Database performance and query optimization 451


SELECT DATA_AREA_NAME, DATA_AREA_VALUE FROM QSYS2.DATA_AREA_INFO
WHERE DATA_AREA_LIBRARY = 'MYLIB';

DATA_QUEUE_ENTRIES table function


The DATA_QUEUE_ENTRIES table function returns one or more messages from the specified data queue.
The messages are not removed from the data queue. The message data is returned as character, UTF-8,
and binary data.
Distributed data management (DDM) data queues are not supported.
The MESSAGE_DATA, MESSAGE_DATA_UTF8, and MESSAGE_DATA_BINARY columns contain identical
values. It is up to the user to determine which data type is most appropriate for working with the result
data.
The values returned for the result columns of the table function are closely related to the values returned
by the Retrieve Data Queue Message (QMHRDQM) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the data queue, and
• *OBJOPR and *READ authority to the data queue.

DATA_QUEUE_ENTRIES ( data-queue
DATA_QUEUE =>

, data-queue-library
DATA_QUEUE_LIBRARY =>

, selection-type
SELECTION_TYPE =>

, key-data
KEY_DATA =>

)
, key-order
KEY_ORDER =>

The schema is QSYS2.

data-queue A character or graphic string containing the name of the data queue.
data- A character or graphic string containing the name of the library containing the data queue.
queue- Can be one of the following special values:
library
*CURLIB The job's current library is used.
*LIBL The library list is used. This is the default.

selection- A character string indicating how the messages are to be returned. If this parameter is
type omitted, ALL is used.

ALL All messages are to be returned in the order based on the type of data queue.
FIFO queues are returned in FIFO order, LIFO queues are returned in LIFO
order, and keyed queues are returned in ascending key order.

452 IBM i: Performance and Query Optimization


FIRST The first message is to be returned. This option is not allowed for a keyed data
queue.
KEY Messages meeting the key criteria are to be returned. This option is only valid
for a keyed data queue.
When this value is specified, key-data and key-order must also be specified.
LAST The last message is to be returned. This option is not allowed for a keyed data
queue.
REVERSE All messages are to be returned in reverse order of the type of data queue. For
example, LIFO queues are returned in FIFO order. This option is not allowed
for a keyed data queue.

key-data A character string containing the data to use as the key for receiving a message from the
data queue. This parameter is required for a keyed data queue. It must not be specified for
a non-keyed data queue.
The length of key-data must be the length specified on the KEYLEN parameter
on the Create Data Queue (CRTDTAQ) command. The KEY_LENGTH column of the
QSYS2.DATA_QUEUE_INFO view contains this value.
When this parameter is specified, key-order must also be specified.
key-order The comparison criteria between the keys of messages on the data queue and the key-
data parameter. Valid values are:

EQ All messages with a key equal to key-data are to be returned.


GE All messages with a key greater than or equal to key-data are to be returned.
GT All messages with a key greater than key-data are to be returned.
LE All messages with a key less than or equal to key-data are to be returned.
LT All messages with a key less than key-data are to be returned.
NE All messages with a key not equal to key-data are to be returned.

This parameter is ignored if key-data is not specified.

The result of the function is a table containing one or more rows with the format shown in the following
table. If no messages are selected, no rows are returned. All the columns are nullable.
Table 91. DATA_QUEUE_ENTRIES table function

Column Name Data Type Description

ORDINAL_POSITION INTEGER The relative position of this row in the result data set.

DATA_QUEUE_LIBRARY VARCHAR(10) The library in which the data queue was found.

DATA_QUEUE VARCHAR(10) The name of the data queue.

MESSAGE_DATA CLOB(64512) The message received from the data queue as character data.

MESSAGE_DATA_UTF8 CLOB(64512) The message received from the data queue represented as character data in
CCSID 1208.
CCSID 1208

MESSAGE_DATA_BINARY BLOB(64512) The message received from the data queue in binary form. This is the raw form of
the data.

KEY_DATA VARCHAR(256) For a keyed data queue. the key value of the returned message. This is the actual
key value, which could be different than the key-data parameter value.
Contains the null value if this is not a keyed data queue.

MESSAGE_ENQUEUE_TIMESTAMP TIMESTAMP(0) The date and time that the message was placed on the data queue.

SENDER_JOB_NAME VARCHAR(28) The qualified job name of the sender.


Contains the null value if no sender information is available for the message.

Database performance and query optimization 453


Table 91. DATA_QUEUE_ENTRIES table function (continued)

Column Name Data Type Description

SENDER_CURRENT_USER VARCHAR(10) The current user profile of the sender.


Contains the null value if no sender information is available for the message.

Example
Look at all the messages in data queue DQ1 in TESTLIB.

SELECT * FROM TABLE(QSYS2.DATA_QUEUE_ENTRIES(


DATA_QUEUE => 'DQ1',
DATA_QUEUE_LIBRARY => 'TESTLIB'))
ORDER BY ORDINAL_POSITION;

DATA_QUEUE_INFO view
The DATA_QUEUE_INFO view returns a row for every data queue.
The information returned is similar to the information available through the Retrieve Data Queue
Description (QMHQRDQD) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the data queue, and
• *OBJOPR and *READ authority to the data queue.
The following table describes the columns in the view. The system name is DTAQ_INFO. The schema is
QSYS2.
Table 92. DATA_QUEUE_INFO view

Column name System column name Data type Description

DATA_QUEUE_LIBRARY DTAQ_LIB VARCHAR(10) Library containing the data queue.

DATA_QUEUE_NAME DTAQ VARCHAR(10) Name of the data queue.

DATA_QUEUE_TYPE DTAQ_TYPE VARCHAR(8) This will be set to one of the following values:

DDM The data queue is a DDM data queue.

STANDARD The data queue is a standard data


queue.

MAXIMUM_MESSAGE_LENGTH MSG_LENGTH INTEGER The maximum length allowed for messages. This
is the value that was specified with the MAXLEN
Nullable keyword on the CRTDTAQ command.
Contains the null value for a DDM data queue.

SEQUENCE SEQUENCE VARCHAR(5) The sequence in which messages can be removed


from the queue.
Nullable
FIFO First-in first-out

KEYED Keyed

LIFO Last-in first-out

Contains the null value for a DDM data queue.

KEY_LENGTH KEY_LENGTH INTEGER The length of the message reference key for a keyed
data queue, in bytes. Values are from 1 to 256.
Nullable
Contains the null value if this is not a keyed queue or
is a DDM data queue.

454 IBM i: Performance and Query Optimization


Table 92. DATA_QUEUE_INFO view (continued)

Column name System column name Data type Description

INCLUDE_SENDER_ID SENDER_ID VARCHAR(3) Indicates if the queue was created to include the
sender ID with sent messages.
Nullable
NO The sender ID is not included when data is
sent to the data queue.

YES The sender ID is included when data is sent


to the data queue.

Contains the null value for a DDM data queue.

CURRENT_MESSAGES CUR_MSGS INTEGER The number of messages currently on the data


queue.
Nullable
Contains the null value for a DDM data queue.

MAXIMUM_MESSAGES MAX_MSGS INTEGER The maximum number of messages that will fit into
the data queue.
Nullable
Contains the null value for a DDM data queue.

SPECIFIED_MAXIMUM_MESSAGES SPEC_MAX INTEGER The maximum number of messages that was


specified on the SIZE keyword of the CRTDTAQ
Nullable command. Can contain the following special values:

-1 *MAX16MB was specified for the data queue


size.

-2 *MAX2GB was specified for the data queue


size.

Contains the null value for a DDM data queue.

INITIAL_MESSAGE_ALLOCATION INIT_ALOC INTEGER The number of messages that will fit into the storage
allocated for the data queue when it is created or
Nullable when it is automatically reclaimed.
Contains the null value for a DDM data queue.

CURRENT_MESSAGE_ALLOCATION CUR_ALOC INTEGER The number of entries that will fit into the data
queue before it is extended. When the queue is
Nullable extended, additional storage is allocated for the
queue. The data queue can be extended until it
reaches the value for the maximum number of
entries allowed.
Contains the null value for a DDM data queue.

FORCE FORCE VARCHAR(3) Whether the data queue is forced to auxiliary


storage when entries are sent or received.
Nullable
NO The data queue is not forced to auxiliary
storage after entries are sent or received.

YES The data queue is forced to auxiliary storage


after entries are sent or received.

Contains the null value for a DDM data queue.

AUTOMATIC_RECLAIM RECLAIM VARCHAR(3) Whether or not the data queue has the amount of
storage allocated for the queue reclaimed when the
Nullable queue is empty.

NO Storage is not reclaimed.

YES Storage is reclaimed when the queue is


empty. The amount of storage allocated will
be set to the initial number of entries.

Contains the null value for a DDM data queue.

LAST_RECLAIM_TIMESTAMP RECLAIM_TS TIMESTAMP The date and time that the last automatic reclaim
was done.
Nullable
Contains the null value for a DDM data queue or
when no reclaim has occurred for a standard data
queue.

Database performance and query optimization 455


Table 92. DATA_QUEUE_INFO view (continued)

Column name System column name Data type Description

ENFORCE_DATA_QUEUE_LOCKS DTAQ_LOCKS VARCHAR(3) Identifies whether IBM-supplied data queue


operations will enforce a lock on the data queue.
Nullable This attribute cannot be specified on the Create Data
Queue (CRTDTAQ) CL Command. The default when
a data queue is created is for locks to be ignored. A
data queue can be locked with the Allocate Object
(ALCOBJ) CL Command. When locks are enforced,
performance can be degraded due to the additional
locking performed by all data queue operations.

NO Locks on the data queue are ignored by IBM-


supplied data queue operations.

YES Locks on the data queue are enforced by


IBM-supplied data queue operations.

Contains the null value for a DDM data queue.

TEXT_DESCRIPTION TEXT VARCHAR(50) The text description of the data queue.

Nullable Contains the null value if there is no text description.

REMOTE_DATA_QUEUE_LIBRARY RMT_DTAQL VARCHAR(10) The name of the library for the remote data queue
on the target system. This is the data queue name
Nullable that was specified on the RMTDTAQ parameter of
the CRTDTAQ command. Can contain the following
special values:

*CURLIB The current library will be used to find


the data queue.

*LIBL The library list will be used to find the


data queue.

Contains the null value for a standard data queue.

REMOTE_DATA_QUEUE RMT_DTAQ VARCHAR(10) The name of the remote data queue on the
target system. This is the data queue name that
Nullable was specified on the RMTDTAQ parameter of the
CRTDTAQ command.
Contains the null value for a standard data queue.

REMOTE_LOCATION REMOTE_LOC VARCHAR(8) The name of the remote location that is used with
this object. This is the name that was specified
Nullable on the RMTLOCNAME parameter of the CRTDTAQ
command. Can contain the following special value:

*RDB The remote location information from the


relational database entry returned in the
relational database entry name field is
used to determine the remote system.

Contains the null value for a standard data queue.

RELATIONAL_DATABASE_NAME RDBNAME VARCHAR(18) The name of the relational database entry that
identifies the target system or target ASP group.
Nullable This is the name that was specified on the RDB
parameter of the CRTDTAQ command.
Contains the null value for a standard data queue
or a data queue that is not an RDB type DDM data
queue.

APPC_DEVICE_DESCRIPTION APPC_DEVD VARCHAR(10) The name of the APPC device description on the
source system that is used with this DDM data
Nullable queue. This is the name that was specified on the
DEV parameter of the CRTDTAQ command. Can
contain the following special value:

*LOC The device associated with the remote


location is used.

Contains the null value for a standard data queue


and for RDB type DDM data queues.

456 IBM i: Performance and Query Optimization


Table 92. DATA_QUEUE_INFO view (continued)

Column name System column name Data type Description

LOCAL_LOCATION LOCAL_LOC VARCHAR(8) The name of the local location. This is the name
that was specified on the LCLLOCNAME parameter of
Nullable the CRTDTAQ command. Can contain the following
special values:

*LOC The device associated with the remote


location is used.

*NETATR The LCLLOCNAME value specified in


the system network attributes is used.

Contains the null value for a standard data queue


and for RDB type DDM data queues.

MODE MODE VARCHAR(8) The mode name used with the remote location name
to communicate with the target system. This is the
Nullable name that was specified on the MODE parameter of
the CRTDTAQ command. Can contain the following
special value:

*NETATR The mode name specified in the


system network attributes is used.

Contains the null value for a standard data queue


and for RDB type DDM data queues.

REMOTE_NETWORK_ID REMOTE_NET VARCHAR(8) The remote network identifier in which the remote
location used to communicate with the target
Nullable system. This is the name that was specified on the
RMTNETID parameter of the CRTDTAQ command.
Can contain the following special values:

*LOC The remote network ID associated


with the remote location is used.

*NETATR The remote network ID value specified


in the system network attributes is
used.

*NONE No remote network ID is used.

Contains the null value for a standard data queue


and for RDB type DDM data queues.

Example
Find the number of messages currently on data queue DQ1 in TESTLIB.

SELECT CURRENT_MESSAGES FROM QSYS2.DATA_QUEUE_INFO


WHERE DATA_QUEUE_LIBRARY = 'TESTLIB' AND DATA_QUEUE_NAME = 'DQ1';

DB_TRANSACTION_INFO view
The DB_TRANSACTION_INFO view returns one row for each commitment definition.
The values returned for the columns in the view are similar to the values returned by the Work with
Commitment Definitions (WRKCMTDFN) CL command and by the Database Transactions and Global
Transactions lists in ACS.
Authorization: None required when the creator of the commitment definition matches the effective
user of the thread. Otherwise, the caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM or QIBM_DB_SYSMON function usage identifier.
The following table describes the columns in the view. The system name is TRANS_INFO. The schema is
QSYS2.
Table 93. DB_TRANSACTION_INFO view

Column Name System Column Name Data Type Description

COMMITMENT_DEFINITION COMMIT_DFN VARCHAR(10) The name of the commitment definition.

Database performance and query optimization 457


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

COMMITMENT_DEFINITION_ TEXT VARCHAR(50) The text description of the commitment


DESCRIPTION definition.
Nullable
Contains the null value if there is no text
description.

COMMITMENT_DEFINITION_ID CMTDEF_ID VARCHAR(10) FOR BIT The ID associated with the commitment
DATA definition. Can contain the following special
values:

*DFTACTGRP This is the commitment


definition for the default
activation group.

*JOB The commitment definition is


shared by activation groups
within a job.

JOB_NAME JOB_NAME VARCHAR(28) The qualified job name that is using commitment
control.

THREAD_ASSOCIATION_STATUS THD_STATUS VARCHAR(11) The thread association status of the *TNSOBJ


scoped commitment definition.
Nullable
*ATTACHED There are threads attached
to the *TNSOBJ scoped
commitment definition.

*UNATTACHED There are no threads attached


to the *TNSOBJ scoped
commitment definition.

Contains the null value if the commitment


definition is not a *TNSOBJ scoped commitment
definition.

LOGICAL_UNIT_OF_WORK_ID LUWID VARCHAR(39) The identifier (ID) of the current logical unit
of work (LUW). This value can be used to
find associated commitment definitions on this
system and on other systems. The logical unit of
work ID (LUWID) is a character string containing
the network-qualified logical unit (LU) name, the
instance number, and the sequence number.
The network-qualified LU name consists of a
network ID with a maximum of 8 characters, a
period delimiter, followed by a LU name with a
maximum of 8 characters. The instance number is
a 12 character value, each character representing
a single hexadecimal digit. The sequence number
is a decimal value with values ranging from 1
through 65535.

458 IBM i: Performance and Query Optimization


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

LOGICAL_UNIT_OF_WORK_STATE LUW_STATE VARCHAR(20) The current state of the logical unit of work (LUW).

COMMIT IN A commit operation is in


PROGRESS progress. The system is
attempting to commit the
resources for this commitment
definition and all downstream
resources associated with this
LUW.

COMMITTED A commit operation is in


progress. The resources for
this commitment definition
and all downstream resources
associated with this LUW have
been committed.

LAST AGENT A commit operation is in


PENDING progress. The resources for
this commitment definition
have been prepared and
the system is waiting for
the last agent selected by
this commitment definition to
return the commit or rollback
decision.

PREPARE IN A commit or prepare operation


PROGRESS is in progress. The system
is attempting to prepare the
resources for this commitment
definition and to prepare
all downstream resources
associated with this LUW.

PREPARED A commit operation is in


progress. The resources for
this commitment definition
and all downstream resources
associated with this LUW have
been prepared.

RESET A commit, rollback, or prepare


operation is not in progress for
this commitment definition.

ROLLBACK IN A rollback operation is in


PROGRESS progress. The system is
attempting to roll back the
committable changes for this
commitment definition and
for all the committable
changes associated with this
commitment definition.

ROLLBACK A rollback operation is


REQUIRED required. The resources
registered to this commitment
definition cannot be used until
the LUW is rolled back.

VOTE READ A commit operation is in


ONLY progress. The commitment
definition had no changes to
commit, the Vote Read Only
commitment option is set
to 'Yes', and all downstream
locations voted read only.
This commitment definition
and any downstream locations
will not participate in the
committed wave during this
commit operation.

STATE_TIMESTAMP STATE_TIME TIMESTAMP(0) The timestamp when the logical unit of work
started or became undecided.
Nullable
Contains the null value if the commitment
definition has performed no work and is not
undecided.

Database performance and query optimization 459


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

LOCK_SPACE_ID LOCKID CHAR(20) The lock space identifier for this commitment
definition.

ACTIVATION_GROUP ACTGRP BIGINT The activation group for this commitment


definition.
Nullable
Contains the null value if the commitment
definition is the job commitment definition
(*JOB), an explicitly named commitment
definition, or a commitment definition that
represents an XA transaction branch with lock
space scoped locks.

ASPGRP ASPGRP VARCHAR(10) The ASP group for this commitment definition. If
*SYSBAS, the commitment definition resides on
the system auxiliary storage pool.

RESOURCE_LOCATION RSC_LOC VARCHAR(6) Indicates whether local or remote resources are


currently under commitment control.

BOTH Both local and remote resources are


under commitment control.

LOCAL Local resources are under


commitment control.

NONE No resources are under commitment


control.

REMOTE Remote resources are under


commitment control.

API resources, and relational database resources


with remote location name *ARDPGM, are
considered to be local, even though they may
represent objects on a remote system. Because
these resources are accessed and updated by
user programs, the system cannot determine
whether these programs access objects on a
remote system.

DEFAULT_LOCK_LEVEL DFT_LCKL VARCHAR(4) The level of record locking on the records in


each database file under commitment control
for the commitment definition when files are
opened using traditional system interfaces. For
files opened using SQL interfaces, the effective
isolation level for each SQL operation determines
the level of record locking that is used.

*ALL Every record that is accessed in


a file under commitment control is
locked until the logical unit of work is
committed or rolled back.

*CHG Every record that is changed in a file


under commitment control is locked
until the logical unit of work is
committed or rolled back.

*CS Every record that is changed in a file


under commitment control is locked
until the logical unit of work is
committed or rolled back. Records that
are accessed but not changed are
locked only until a different record is
accessed.

USER_NAME USER_NAME VARCHAR(10) The user profile that started the transaction.

460 IBM i: Performance and Query Optimization


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

LOCAL_CHANGES_PENDING LOCAL_PEND VARCHAR(3) Indicates whether this commitment definition has


local changes pending. A local pending change
means:
• One or more record level changes are pending.
SQL statements run against the relational
database might or might not have committable
changes to the local database.
• One or more object level changes are pending.
• An API resource is registered that does not
allow save-while-active requests to perform
normally or does not allow independent ASPs
to be quiesced.

NO This commitment definition has no local


changes pending.

YES This commitment definition has local


changes pending.

LOCAL_JOURNAL_CHANGES_PENDING LOCAL_JRN VARCHAR(3) Indicates this commitment definition has journals


with changes pending.
This means that one or more local journals have
changes pending.

NO This commitment definition has no local


journal changes pending.

YES This commitment definition has local


journal changes pending.

LOCAL_RECORD_CHANGES_PENDING LOCAL_RCD VARCHAR(3) Indicates whether this commitment definition has


records with changes pending.
This means that one or more local records have
insert, update, or delete changes pending.

NO This commitment definition has no local


record level changes pending.

YES This commitment definition has local


record level changes pending.

LOCAL_OBJECT_CHANGES_PENDING LOCAL_OBJ VARCHAR(3) Indicates whether this commitment definition has


objects with changes pending.
This means that one or more local objects have
changes pending.

NO This commitment definition has no local


object level changes pending.

YES This commitment definition has local


object level changes pending.

LOCAL_API_CHANGES_PENDING LOCAL_API VARCHAR(3) Indicates whether this commitment definition has


local API changes pending.
This means that one or more API resources are
registered that do not allow save-while-active
requests to perform normally or do not allow
independent ASPs to be quiesced.

NO This commitment definition has no local


API resource changes pending.

YES This commitment definition has local API


resource changes pending.

Database performance and query optimization 461


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

LOCAL_RDB_CHANGES_PENDING LOCAL_RDB VARCHAR(3) Indicates whether this commitment definition has


local RDB changes pending.
This means that one or more record or
object level changes are pending for a local
RDB resource. SQL statements run against
the relational database may or may not have
committable changes to the local database.

NO This commitment definition has no local


RDB changes pending.

YES This commitment definition has local RDB


changes pending.

REMOTE_CHANGES_PENDING RMT_PEND VARCHAR(3) Indicates whether this commitment definition


has remote changes pending. A remote pending
change means:
• One or more record or object level changes are
pending for an RDB resource. SQL statements
run against the relational database may or may
not have committable changes to the remote
database.
• One or more record or object level changes are
pending for a TCP/IP connection resource.
• One or more record or object level changes are
pending for a remote file resource.
• One or more record or object level changes are
pending for a conversation resource.

NO This commitment definition has no


remote changes pending.

YES This commitment definition has remote


changes pending.

REMOTE_RDB_CHANGES_PENDING RMT_RDB VARCHAR(3) Indicates whether this commitment definition has


remote RDB changes pending. This means:
• One or more record or object level changes
are pending for a remote RDB resource. SQL
statements run against the relational database
may or may not have committable changes to
the remote database.
• One or more record or object level changes are
pending for a TCP/IP connection resource.

NO This commitment definition has no


remote RDB changes pending.

YES This commitment definition has remote


RDB changes pending.

REMOTE_FILE_CHANGES_PENDING RMT_FILE VARCHAR(3) Indicates whether this commitment definition has


remote file changes pending. This means that
one or more record or object level changes are
pending for a remote file resource.

NO This commitment definition has no


remote file changes pending.

YES This commitment definition has remote


file changes pending.

462 IBM i: Performance and Query Optimization


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

REMOTE_CONVERSATION_CHANGES_PENDING RMT_CONV VARCHAR(3) Indicates whether this commitment definition


has remote conversation changes pending. This
means that one or more record or object level
changes are pending for a conversation resource.
SQL statements run against the relational
database may or may not have committable
changes to the remote database.

NO This commitment definition has no


remote conversation changes pending.

YES This commitment definition has remote


conversation changes pending.

ROLE ROLE VARCHAR(19) Indicates the role that this location is playing in
the transaction program network.
Nullable
AGENT This location is a leaf in the
transaction program network
and it has no subordinate
locations.

CASCADER This location is an intermediate


node in the transaction program
network and it has subordinate
locations. The commit or
rollback operation did not start
at this location.

INITIATOR This location started the commit


or rollback operation and is
at the root of the transaction
program network.

LAST AGENT This location is a leaf in the


transaction program network
and it is the last agent, which
decides whether to commit or to
roll back the logical unit of work.

LAST AGENT This location is a middle node


CASCADER in the transaction program
network and it is the last agent,
which decides whether the
logical unit of work is committed
or rolled back. This location also
can delegate another location of
its choice to be the last agent.

LOCAL This location is the only location


with resources registered to the
commitment definition.

X/OPEN This location is a leaf


AGENT in the transaction program
network. The commit operation
was initiated by an X/Open
transaction manager.

X/OPEN This location is a middle


CASCADER node in the transaction
program network. The commit
operation was initiated by an X/
Open transaction manager and
this location has subordinate
locations.

Contains the null value if the role is not


recognized.

RESYNC_IN_PROGRESS RESYNCING VARCHAR(3) Indicates whether this commitment definition


is resynchronizing resources that are associated
with the logical unit of work.

NO This commitment definition is not


resynchronizing resources.

YES This commitment definition is


resynchronizing resources.

Database performance and query optimization 463


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

HEURISTIC_OPERATION HEUR_OPER VARCHAR(20) The user-specified operation (resulting from


a heuristic decision) performed against this
Nullable commitment definition's resources and against all
of the downstream resources associated with the
logical unit of work.

COMMIT IN The user forced a commit


PROGRESS operation that has not yet
completed.

FORCED The user forced a commit


COMMIT operation.

FORCED The user forced a rollback


ROLLBACK operation.

ROLLBACK IN The user forced a rollback


PROGRESS operation that has not yet
completed.

Contains the null value if the user has not


specified a heuristic operation.

MIRROR_ACTIVE MIRROR_ACT VARCHAR(3) Indicates whether the commitment definition


has a Db2 Mirror resource registered under
commitment control.

NO The commitment definition has no


Db2 Mirror resource registered under
commitment control.

YES The commitment definition has Db2


Mirror resource registered under
commitment control.

MIRROR_ERROR MIRROR_ERR VARCHAR(19) Indicates whether commitment control has


detected a Db2 Mirror error.
Nullable
BLOCKED The Db2 Mirror state
was BLOCKED when the
error was detected.

COMMUNICATION A communication error


ERROR was detected.

NO ERROR No error has been


detected.

TRACKING The Db2 Mirror state


was TRACKING when
the error was detected.

Contains the null value if MIRROR_ACTIVE is NO.

MIRROR_ERROR_IASP MIRROR_EI INTEGER The IASP number of the IASP where commitment
control detected a Db2 Mirror error.
Nullable
Contains the null value if MIRROR_ACTIVE is NO
or if commitment control has not detected a Db2
Mirror error for an IASP.

MIRROR_TRACKING_IASP MIRROR_TI INTEGER The IASP number of the IASP where commitment
control detected the Db2 Mirror state was
Nullable TRACKING.
Contains the null value if MIRROR_ACTIVE is NO
or if commitment control has not detected an
IASP where the Db2 Mirror state is TRACKING.

464 IBM i: Performance and Query Optimization


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

JOB_ACTIVE JOB_ACTIVE VARCHAR(6) Indicates whether this commitment definition is


part of an active job.

NO This commitment definition is not


part of an active job. The job was
ended before all logical units of work
were complete.

SERVER The job that the commitment


definition was part of has ended,
and the commitment definition has
been made part of a database server
job. The SERVER_JOB_NAME column
contains the name of the database
server job.

YES This commitment definition is part of


an active job.

SERVER_JOB_NAME SERVER_JOB VARCHAR(28) Qualified job name of the database server job of
which this commitment definition is a part.
Nullable
Contains the null value if the commitment
definition is not part of a database server job.

LOCK_SCOPE LOCK_SCOPE VARCHAR(7) Indicates where the locks acquired on behalf of


the commitment definition are scoped.
Nullable
*ACTGRP The commitment definition has an
activation group level scope.

*EXPL The commitment definition is


explicitly named scope.

*JOB The commitment definition has a


job level scope.

*TNSOBJ The commitment definition has a


transaction object level scope (XA).

Contains the null value if the lock scope is not


recognized.

LOCK_WAIT_TIME LOCK_WAIT INTEGER The maximum number of seconds that the system
waits to acquire a lock requested on behalf of this
commitment definition. Lock wait time values that
are specified or defaulted using system interfaces
other than the xa_open API are used if they are
smaller than this value, or if this value is zero.

LOCK_LIMIT LOCK_LIMIT BIGINT Indicates the maximum number of records which


can be locked within a transaction. If multiple
journals are involved in the transaction, this limit
applies to each journal, not the transaction as a
whole.
The COMMITMENT_CONTROL_LOCK_LIMIT
QAQQINI option can be used to configure this
value before commitment control is started.

NESTING_LEVEL_DEPTH NEST_LEVEL INTEGER The current nesting depth of all nested


transactions for this commitment definition.

NUMBER_SAVEPOINTS SAVEPOINTS INTEGER The number of active savepoints.

COMMIT_ROLLBACK_END CR_END VARCHAR(3) Indicates if COMMIT, ROLLBACK, and


ENDCMTCTL are allowed to be executed.

NO COMMIT, ROLLBACK, and ENDCMTCTL


are not allowed.

YES COMMIT, ROLLBACK, and ENDCMTCTL


are allowed.

Database performance and query optimization 465


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

EXPLICIT_COMMIT_ROLLBACK EXPL_CR VARCHAR(3) Indicates if an explicit COMMIT or ROLLBACK was


executed.

NO An explicit COMMIT or ROLLBACK has not


been executed.

YES An explicit COMMIT or ROLLBACK has


been executed.

SQL_DYNAMIC_COMMIT SQL_DYNC VARCHAR(3) Indicates if an SQL Dynamic COMMIT was


executed.

NO An SQL dynamic COMMIT has not been


executed.

YES An SQL dynamic COMMIT has been


executed.

SQL_DYNAMIC_ROLLBACK SQL_DYNR VARCHAR(3) Indicates if an SQL Dynamic ROLLBACK was


executed.

NO An SQL dynamic ROLLBACK has not been


executed.

YES An SQL dynamic ROLLBACK has been


executed.

SQL_HOLD_COMMIT SQL_HOLD VARCHAR(3) Indicates the SQL HOLD value used on the call to
COMMIT.

NO SQLHOLD(NO) specified on COMMIT call.

YES SQLHOLD(YES) specified on COMMIT call.

COMMIT_DURABLE DURABLE VARCHAR(3) Indicates whether commit operations are


guaranteed to be durable.

NO The commit operation is not durable.


Atomicity of the transaction is
guaranteed, but one or more transactions
may be lost in the event of a system
failure.

YES The commit operation is durable. When


the transaction is committed, the
transaction is guaranteed to persist on
the system.

NUMBER_COMMITS COMMIT_OPS BIGINT The total number of commit operations


performed since this commitment definition was
Nullable created. This number includes commit operations
initiated by both the user and the operating
system. Returns 2,147,483,648 if the number of
commits has exceeded 2,147,483,647.
Contains the null value if an IPL has been
performed on the system since the commitment
definition was created.

NUMBER_ROLLBACKS ROLLB_OPS BIGINT The total number of rollback operations


performed since this commitment definition was
Nullable created. This number includes rollback operations
initiated by both the user and the operating
system. Returns 2,147,483,648 if the number of
rollbacks has exceeded 2,147,483,647.
Contains the null value if an IPL has been
performed on the system since the commitment
definition was created.

DEFAULT_JOURNAL_LIBRARY DFT_JRNLIB VARCHAR(10) The name of the library in which the default
journal is located.
Nullable
Contains the null value if there is no default
journal.

466 IBM i: Performance and Query Optimization


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

DEFAULT_JOURNAL_NAME DFT_JRN VARCHAR(10) The name of the default journal that was specified
when the commitment definition was created. All
Nullable logical unit of work (LUW) entries are placed in
this journal.
Contains the null value if there is no default
journal.

NOTIFY_OBJECT_TYPE NOTIFY_TYP VARCHAR(7) Type of notify object for the commitment


definition.
Nullable
*DTAARA The notify object is a data area.

*FILE The notify object is a database file


member

*MSGQ The notify object is a message


queue.

Contains the null value if there is no notification


object.

NOTIFY_OBJECT_LIBRARY NOTIFY_LIB VARCHAR(10) The name of the library in which the notify object
for the commitment definition can be located.
Nullable
Contains the null value if there is no notification
object.

NOTIFY_OBJECT NOTIFY_OBJ VARCHAR(10) The name of the object to which notification


is sent regarding the status of the commitment
Nullable definition.
Contains the null value if there is no notification
object.

NOTIFY_OBJECT_MEMBER NOTIFY_MBR VARCHAR(10) The name of the database file member that is the
notify object for the commitment definition.
Nullable
Contains the null value if there is no notification
object or NOTIFY_OBJECT_TYPE is not *FILE.

Database performance and query optimization 467


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

WAIT_FOR_OUTCOME WAIT_OUTC VARCHAR(17) This commitment option indicates how


this system handles resynchronization if a
Nullable communications or remote system failure occurs
during a commit or rollback operation. This value
is set to WAIT when commitment control is
started and can be changed using the Change
Commitment Options (QTNCHGCO) API. Note:
If the commitment definition has a Wait for
Outcome value of WAIT or inherits a value of
WAIT, the value of the ACCEPT_VOTE_RELIABLE
commitment option is ignored, and the system
behaves as though the ACCEPT_VOTE_RELIABLE
commitment option is NO.

INHERIT When this system is the initiator of


OR the commit or rollback operation,
NOWAIT the INHERIT OR NOWAIT value has
the same effect as the NOWAIT
value. When this system is not the
initiator and the initiator supports
the presumed abort protocol, the
Wait for Outcome value is inherited
from the initiator. When this system
is not the initiator and the initiator
does not support the presumed
abort protocol, the INHERIT OR
NOWAIT value has the same effect
as the NOWAIT value.

INHERIT When this system is the initiator of


OR WAIT the commit or rollback operation,
the INHERIT OR WAIT value has
the same effect as the WAIT
value. When this system is not the
initiator and the initiator supports
the presumed abort protocol, the
Wait for Outcome value is inherited
from the initiator. When this system
is not the initiator and the initiator
does not support the presumed
abort protocol, the INHERIT OR
WAIT value has the same effect as
the WAIT value.

NOWAIT This system attempts to


resynchronize one time before
allowing the commit or rollback
operation to complete. If
the initial attempt fails, the
resynchronization is completed in
a database server job, and the
application is not notified of the
result of the resynchronization.
Resynchronizations required with
the last agent location always wait
regardless of the current status of
the wait for outcome option.

WAIT This system completes


resynchronization before allowing
the commit or rollback operation to
complete.

Contains the null value if the Wait for Outcome


option was not specified for the commitment
definition.

468 IBM i: Performance and Query Optimization


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

PROBLEM_ACTION ACTION VARCHAR(8) Indicates what this system does if another


system, which controls whether the logical unit
of work should commit or rollback, sends this
system an unrecognized message or detects
damage in the logical unit of work. This value
is set to ROLLBACK when commitment control
is started and can be changed using the Change
Commitment Options (QTNCHGCO) API.

COMMIT The changes associated with this


logical unit of work are committed.

ROLLBACK The changes associated with this


logical unit of work are rolled back.

VOTE_READ_ONLY_PERMITTED VOTE_RO VARCHAR(3) Indicates whether this system can vote read-only
in response to a commit operation started on
another system. Note: If this system votes read-
only, control is not returned to the application
until this system receives a message from the
starting system containing an indicator that the
next logical unit of work has started. The length
of the delay in regaining control depends on the
application running on the starting system. This
value is set to NO when commitment control is
started and can be changed using the Change
Commitment Options (QTNCHGCO) API.

NO This system cannot vote read-only.

YES This system can vote read-only.

END_JOB_ACTION ENDJOB_ACT VARCHAR(8) Indicates what this system does if the logical
unit of work is in an undecided state and the job
Nullable is ending abnormally. This value is set to WAIT
when commitment control is started and can be
changed using the Change Commitment Options
(QTNCHGCO) API.

COMMIT This system commits the changes


made to the logical of work.

ROLLBACK This system rolls back the changes


made to the logical unit of work.

WAIT The system gets the commit or


rollback decision from the system
that started the operation. Based
on that decision, this system
commits or rolls back the changes
made to the logical unit of work
before ending the job. Heuristic
operations can be performed
if the time spent waiting is
unacceptable.

Contains the null value if the end job action is not


known.

LAST_AGENT_PERMITTED LAST_AGENT VARCHAR(6) Indicates whether a last agent can be selected


when one is eligible to be selected during a
Nullable commit operation. A last agent is eligible to be
selected at the location that initiates a commit
operation, and at locations that are selected as
a last agent by the location that propagates the
commit operation to that location. This value
is set to SYSTEM when commitment control is
started and can be changed using the Change
Commitment Options (QTNCHGCO) API.

NO The system is not allowed to select a


last agent.

SYSTEM The system is allowed to select a last


agent.

Contains the null value if the last agent permitted


value is not known.

Database performance and query optimization 469


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

LEAVE_OUT_OK LEAVE_OUT VARCHAR(3) The commitment option that indicates whether


it is OK to leave this system out of a
commit operation initiated at another system.
If this system indicates it can be left out, no
communications flows are sent to this system
during subsequent commit or rollback operations
until a data flow is received from the initiator.
Also, control is not returned to the application
until the data flow is received. This value is set
to NO when commitment control is started and
can be changed using the Change Commitment
Options (QTNCHGCO) API.

NO This system may not be left out of


subsequent logical units of work.

YES This system may be left out of


subsequent logical units of work.

ACCEPT_VOTE_RELIABLE ACCEPT_VR VARCHAR(3) Indicates whether this system accepts the vote
reliable indicator if it is received from its agents
during the prepare wave of a commit operation.
The vote reliable indicator indicates that it is
unlikely that a heuristic decision will be made
at the agent if a failure occurs before the
committed wave completes. If an agent sends
the vote reliable indicator, and this location
accepts it, performance is improved because one
communications flow is eliminated and control is
returned to the application before the committed
wave is completed for that agent. However, if a
heuristic decision is made at that agent which
causes heuristic damage, the application at this
location will not receive an error message if the
Accept vote reliable commitment option is set to
YES. This value is set to YES when commitment
control is started and can be changed using the
Change Commitment Options (QTNCHGCO) API.
If the commitment definition has a Wait for
outcome value of Wait or inherits a value of Wait,
the value of the Accept vote reliable commitment
option is ignored, and the system behaves as
though the Accept vote reliable commitment
option is No.

NO This system does not accept the vote


reliable indicator.

YES This system accepts the vote reliable


indicator.

RECYCLE_COUNT RECYCLECNT INTEGER The number of times that this commitment


definition has been recycled as a spare.

470 IBM i: Performance and Query Optimization


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

RECEIVED_DRDA_SYNCTYPE RCV_SYNC VARCHAR(17) The two-phase commitment control


synchronization type received by commitment
Nullable control on the target-side of a DRDA connection.

COMMITTED The application requester


committed its unit or work.

FORGET The application requester


issued a forget request.

MIGRATE The application requester


issued a migrate request.

NEW UNIT OF The application requester is


WORK requesting a new unit of
work.

PREPARE TO The application requester is


COMMIT requesting the unit of work
be prepared to commit.

REQUEST TO The application requester is


COMMIT requesting the unit of work
be committed.

ROLLBACK The application requester is


requesting the unit of work
be rolled back.

Contains the null value if no two-phase


commitment control requests have been
received.

RETURNED_DRDA_SYNCTYPE RET_SYNC VARCHAR(17) The two-phase commitment control


synchronization type returned by commitment
Nullable control on the target-side of a DRDA connection.

COMMITTED The application server


committed its unit or work.

FORGET The application server


returned a forget request.

MIGRATE The application server


returned a migrate request.

REQUEST TO The application server is


COMMIT returning the unit of work be
committed.

ROLLBACK The application server is


returning the unit of work be
rolled back.

Contains the null value if no two-phase


commitment control requests have been
returned.

XA_CONNECTION_TYPE XA_TYPE VARCHAR(8) Indicates whether this commitment definition


was created in an SQL Server Job for the
Nullable purposes of running XA transactions.

CLI The XA transactions are being


performed in an SQL Server Job
over a CLI connection.

EMBEDDED The XA transactions are being


performed in an SQL Server
Job over an embedded SQL
connection.

NONE The XA transactions are not


performed in an SQL Server Job.

Contains the null value if the commitment


definition is not a *TNSOBJ scoped commitment
definition.

Database performance and query optimization 471


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

XA_RMID XA_RMID INTEGER The resource manager ID (RMID). The unique


number is assigned by the transaction manager to
Nullable identify this instance of the XA resource manager
within the thread of control. This RMID is passed
on subsequent calls to XA routines to identify
the resource manager. The identifier remains
constant until the transaction manager in this
thread closes the resource manager.
Contains the null value if the commitment
definition is not a *TNSOBJ scoped commitment
definition.

XA_TRANSACTION_MANAGER XA_MANAGER VARCHAR(10) The name of the transaction manager that started
the XA transaction branch represented by this
Nullable commitment definition.
Contains the null value if the commitment
definition is not a *TNSOBJ scoped commitment
definition or if the transaction manager name was
not specified for the commitment definition.

XA_RDB_NAME XA_RDB VARCHAR(18) The relational database name (RDB) associated


with the XA transaction represented by this
Nullable commitment definition.
Contains the null value if the commitment
definition is not a *TNSOBJ scoped commitment
definition.

XA_TRANSACTION_BRANCH_STATE XA_STATE VARCHAR(23) Indicates the state of the XA transaction branch


represented by this commitment definition.
Nullable
ACTIVE One or more threads
of control are actively
associated with the
transaction branch.

IDLE No threads of control are


actively associated with
the transaction branch.

PREPARED The transaction branch


has been prepared.

ROLLBACK ONLY The transaction branch is


required to roll back.

HEURISTICALLY The transaction branch


COMPLETED has been heuristically
committed or rolled back.

Contains the null value if the commitment


definition is not a *TNSOBJ scoped commitment
definition.

XA_XID_FORMAT_ID XA_FMTID VARBINARY(4) The hex value of the format identifier portion of
the XA transaction identifier (XID).
Nullable
Contains the null value if the commitment
definition is not a *TNSOBJ scoped commitment
definition.

XA_XID_GLOBAL_TRANSACTION_ID XA_GTRID VARBINARY(64) The hex value of the global transaction identifier
(GTRID) portion of the XA transaction identifier
Nullable (XID).
Contains the null value if the commitment
definition is not a *TNSOBJ scoped commitment
definition.

XA_XID_BRANCH_QUALIFIER XA_BQUAL VARBINARY(64) The hex value of the branch qualifier (BQUAL)
portion of the XA transaction identifier (XID).
Nullable
Contains the null value if the commitment
definition is not a *TNSOBJ scoped commitment
definition.

472 IBM i: Performance and Query Optimization


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

XA_OPEN_SQL_HOLD XA_SQLHOLD CHAR(1) Indicates how SQL cursors are affected by some
XA operations. Specified on the db2xa_open() API
Nullable xainfo string SQLHOLD keyword.

A • db2xa_commit() and db2xa_rollback():


Cursors are not affected since
db2xa_end() already closed them.
• db2xa_end() :
All cursors are closed.

C • db2xa_commit() and db2xa_rollback():


Cursors declared WITH HOLD are held
open. Cursors not declared WITH HOLD
are closed.
• db2xa_end():
All cursors are held open.

E • db2xa_commit():
Cursors declared WITH HOLD are held
open. Cursors not declared WITH HOLD
are closed.
• db2xa_rollback():
All cursors are closed.
• db2xa_end():
Cursors declared WITH HOLD are held
open. Cursors not declared WITH HOLD
are closed.

L • db2xa_commit():
If the relational database resides on an
IBM i, all cursors are left open.
Otherwise, cursors declared WITH HOLD
are left open and cursors not declared
WITH HOLD are closed.
• db2xa_rollback():
If the relational database resides on an
IBM i, all cursors are left open.
Otherwise, all cursors are closed.
• db2xa_end():
All cursors are held open.

N • db2xa_commit():
Cursors declared WITH HOLD are held
open. Cursors not declared WITH HOLD
are closed.
• db2xa_rollback():
All cursors are closed.
• db2xa_end():
All cursors are held open.

Y • db2xa_commit() and db2xa_rollback():


If the relational database resides on an
IBM i, all cursors are left open.
Otherwise, the operation will fail.
• db2xa_end():
All cursors are held open.

Contains the null value if the commitment


definition is not a *TNSOBJ scoped commitment
definition or it is a *TNSOBJ scoped commitment
definition but not one where SQLHOLD was
specified on the db2xa_open() API.

Database performance and query optimization 473


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

XA_OPEN_TBLCS XA_TBLCS CHAR(1) Indicates whether loosely coupled threads


of control (those working on transaction
Nullable branches with the same global transaction
identifier (GTRID), but different branch qualifiers
(BQUALs)), share locks. This is what was specified
on xa_open() API.

N Locks are not shared. Resource deadlock


may occur between the transaction
branches.

S Locks are shared. Resource deadlock will


not occur between the transaction branches.

Contains the null value if the commitment


definition is not a *TNSOBJ scoped commitment
definition or it is a *TNSOBJ scoped commitment
definition but not one where TBLCS was specified
on the xa_open() API.

XA_THREAD_OF_CONTROL XA_THDCTL VARCHAR(10) The thread of control for the XA transaction


branch represented by this commitment
Nullable definition.

CONNECTION The SQL connection is the


XA thread of control. The XA
transaction branch represented
by this commitment definition
was started by the
SQLSetConnectAttr API or
by a remote system that
established an SQL connection
to this system. All SQL work
requested using the connection
that started the transaction
branch becomes part of the
transaction branch regardless
of requesting thread.

THREAD The thread is the XA thread


of control. The XA transaction
branch represented by this
commitment definition was
started by the xa_start or
db2xa_start API. All SQL
work requested by the thread
that started the transaction
branch becomes part of the
transaction branch regardless
of which SQL connection is
used to perform that work.

Contains the null value if the commitment


definition is not a *TNSOBJ scoped commitment
definition.

XA_THREAD_ASSOCIATION_COUNT XA_THDCNT BIGINT The number of threads or SQL connections


currently associated with the XA transaction
Nullable branch represented by this commitment
definition. The associations may be active or
suspended.
Contains the null value if the commitment
definition is not a *TNSOBJ scoped commitment
definition.

474 IBM i: Performance and Query Optimization


Table 93. DB_TRANSACTION_INFO view (continued)

Column Name System Column Name Data Type Description

XA_LOCK_SHARING XA_LOCKSHR VARCHAR(3) Specifies whether locks are shared with loosely
coupled transaction branches. A loosely coupled
Nullable transaction branch is one with a transaction
identifier (XID) that has the same global
transaction identifier (GTRID) but a different
branch qualifier (BQUAL).

NO This commitment definition does not


share locks with loosely coupled
transaction branches.

YES This commitment definition shares


locks with loosely coupled transaction
branches.

Contains the null value if the commitment


definition is not a *TNSOBJ scoped commitment
definition.

XA_LOCK_SPACE_HANDLE XA_LOCKSP INTEGER The lock space associated space handle.

Nullable Contains the null value if the commitment


definition is not a *TNSOBJ scoped commitment
definition.

XA_TRANSACTION_TIMEOUT XA_TIMEOUT INTEGER The number of seconds that an XA transaction is


allowed to exist before being automatically rolled
Nullable back by the system.
Contains the null value if the commitment
definition is not a *TNSOBJ scoped commitment
definition or if the number of seconds is 0.

Example
• Show all jobs that have local work that has not been committed. The rows that are returned are not
ordered.

SELECT *
FROM QSYS2.DB_TRANSACTION_INFO
WHERE LOCAL_CHANGES_PENDING = 'YES';

• Show all jobs that have a commitment definition. Order the returned rows by job name, then job user,
then by job number.

SELECT *
FROM QSYS2.DB_TRANSACTION_INFO
ORDER BY SUBSTR(SUBSTR(JOB_NAME,8),POSSTR(SUBSTR(JOB_NAME,8),'/')+1), --job name
SUBSTR(JOB_NAME,8,POSSTR(SUBSTR(JOB_NAME,8),'/')-1), -- job user
SUBSTR(JOB_NAME,1,6) -- job number
;

DB_TRANSACTION_JOURNAL_INFO table function


The DB_TRANSACTION_JOURNAL_INFO table function returns the status of journal resources under
commitment control for a commitment definition.
The information returned is similar to the values shown by Display Journal Status within the Work with
Commitment Definitions (WRKCMTDFN) CL command.
Authorization: None required when the creator of the commitment definition matches the effective
user of the thread. Otherwise, the caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM or QIBM_DB_SYSMON function usage identifier.

DB_TRANSACTION_JOURNAL_INFO ( lock-space-id )
LOCK_SPACE_ID =>

The schema is QSYS2.

Database performance and query optimization 475


lock-space-id A character string that contains the lock space identifier of the commitment definition to
be returned.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 94. DB_TRANSACTION_JOURNAL_INFO table function

Column Name Data Type Description

JOURNAL_LIBRARY VARCHAR(10) The name of the library that contains the journal.

JOURNAL_NAME VARCHAR(10) The name of the journal.

COMMIT_CYCLE DECIMAL(21,0) The commit cycle identifier of the current logical unit
of work (LUW) for this journal. The commit cycle
identifier is the sequence number of the journal entry
that corresponds to the beginning of the current LUW
for the commitment definition.
Contains the null value if no changes have been made
to local database files under commitment control, and
no user journal entries have been sent to this journal
on behalf of an API resource that is journaled to this
journal during this LUW.

RECORD_LOCKS BIGINT The number of record locks held by this commitment


definition for files journaled to this journal. This
number is kept current during the entire transaction.
When a commit or rollback is requested, the number
will decrease to show progress as locks are released.

PENDING_CHANGES BIGINT The number of changes that have yet to be committed


or rolled back for the journal. This number is kept
current during the entire transaction. When a rollback
is requested, the number will decrease to show
progress as the rollback occurs.

RECORD_ROLLBACK_STARTED TIMESTAMP(0) The timestamp when record level rollback started for
the journal.
Contains the null value if a rollback has not started.

RECORD_ROLLBACK_PERCENT INTEGER The percentage of record level rollback processing that


has completed for the journal. A value of 100 means
record level rollback has completed for this journal,
but other steps in the current commit or rollback
operation may still be in progress for this or other
journals related to this commitment definition.
Contains the null value if no rollback is in progress, or
rollback has not yet started for this journal.

INDEX_ENTRIES INTEGER The number of index entries in internal indexes used


by this commitment definition. This number is kept
current during the entire transaction. When a rollback
is requested, the number will decrease to show
progress as the rollback occurs.

INDEX_CLEANUP_STARTED TIMESTAMP(0) The timestamp when the index cleanup started for the
journal.
Contains the null value if cleanup has not started.

INDEX_CLEANUP_PERCENT INTEGER The percentage of index cleanup that has completed


for the journal. A value of 100 means cleanup has
completed for this journal, but other steps in the
current commit or rollback operation are still in
progress for this or other journals related to this
commitment definition.
Contains the null value if no cleanup is in progress, or
cleanup has not yet started for this journal.

RECORD_UNLOCK_STARTED TIMESTAMP(0) The timestamp when the record unlock processing


started for the journal.
Contains the null value if unlock processing has not
started.

476 IBM i: Performance and Query Optimization


Table 94. DB_TRANSACTION_JOURNAL_INFO table function (continued)

Column Name Data Type Description

RECORD_UNLOCK_PERCENT INTEGER The percentage of record unlock processing that has


completed for the journal. A value of 100 means
unlock processing has completed for this journal, but
other steps in the current commit or rollback operation
are still in progress for this or other journals related to
this commitment definition.
Contains the null value if no record unlock processing
is in progress, or it has not yet started for this journal.

Example
• Show the status of journal resources under commitment control for a specific lock space ID.

SELECT * FROM TABLE(QSYS2.DB_TRANSACTION_JOURNAL_INFO('UDB_010000000000A07F'));

DB_TRANSACTION_OBJECT_INFO table function


The DB_TRANSACTION_OBJECT_INFO table function returns the object level status of objects under
commitment control for a commitment definition.
An object can appear in the result more than once if it was changed more than once during the current
logical unit of work.
The information returned is similar to the values shown by Display Object Level Status within the Work
with Commitment Definitions (WRKCMTDFN) CL command.
Authorization: None required when the creator of the commitment definition matches the effective
user of the thread. Otherwise, the caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM or QIBM_DB_SYSMON function usage identifier.

DB_TRANSACTION_OBJECT_INFO ( lock-space-id )
LOCK_SPACE_ID =>

The schema is QSYS2.

lock-space-id A character string that contains the lock space identifier of the commitment definition to
use.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 95. DB_TRANSACTION_OBJECT_INFO table function

Column Name Data Type Description

ORDINAL_POSITION INTEGER The relative position of this row in the result data set.
This indicates the order in which the object changed,
with 1 being the oldest row.

OBJECT_LIBRARY VARCHAR(10) The name of the library that contains the object.

OBJECT_NAME VARCHAR(10) The name of the object under commitment control for
the commitment definition.

OBJECT_TYPE VARCHAR(7) The type of object.

OPERATION VARCHAR(42) A description of the command or operation that caused


a committable change to be made to the object.

Example
• View all the objects associated with a given commit definition.

Database performance and query optimization 477


SELECT * FROM TABLE(QSYS2.DB_TRANSACTION_OBJECT_INFO('UDB_0100000000000001'))
ORDER BY ORDINAL_POSITION;

DB_TRANSACTION_RECORD_INFO table function


The DB_TRANSACTION_RECORD_INFO table function returns the record level status of local database
files under commitment control for a commitment definition.
The information returned is similar to the values shown by Display Record Level Status within the Work
with Commitment Definitions (WRKCMTDFN) CL command.
Authorization: None required when the creator of the commitment definition matches the effective
user of the thread. Otherwise, the caller must have *JOBCTL special authority or be authorized to the
QIBM_DB_SQLADM or QIBM_DB_SYSMON function usage identifier.

DB_TRANSACTION_RECORD_INFO ( lock-space-id )
LOCK_SPACE_ID =>

The schema is QSYS2.

lock-space-id A character string that contains the lock space identifier of the commitment definition to
use.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 96. DB_TRANSACTION_RECORD_INFO table function

Column Name Data Type Description

LIBRARY_NAME VARCHAR(10) The name of the library that contains the file.

FILE_NAME VARCHAR(10) The name of the local database file under commitment
control for the commitment definition.

MEMBER_NAME VARCHAR(10) The name of the member in the file.

FILE_CHANGES_COMMITTED BIGINT The total number of record level changes to the file
that have been committed.
Returns the value 32768 when more than 32767
changes have been committed.
Contains the null value if an IPL has been performed
on the system since the commitment definition was
created.

FILE_CHANGES_ROLLED_BACK BIGINT The total number of record level changes to the file
that have been rolled back.
Returns the value 32768 when more than 32767
changes have been rolled back.
Contains the null value if an IPL has been performed
on the system since the commitment definition was
created.

FILE_CHANGES_PENDING BIGINT The total number of record level changes to the


file that are pending a commit or rollback for the
commitment definition.
Returns the value 32,768 when more than 32767
changes are pending.
Contains the null value if an IPL has been performed
on the system since the commitment definition was
created.

478 IBM i: Performance and Query Optimization


Table 96. DB_TRANSACTION_RECORD_INFO table function (continued)

Column Name Data Type Description

LOCK_LEVEL VARCHAR(5) The level of record locking for this file.

*ALL Records that are read, updated, deleted,


and inserted are locked until the logical
unit of work is committed or rolled back.
Uncommitted changes in other jobs cannot
be seen.

*CHG Records that are updated, deleted, and


inserted are locked until the logical unit
of work is committed or rolled back.
Uncommitted changes in other jobs can be
seen.

*CS Records that are updated, deleted, and


inserted are locked until the logical unit
of work is committed or rolled back. A
record that is read but not updated is locked
until the next record is read. Uncommitted
changes in other jobs cannot be seen

*CSKL Records that are updated, deleted, and


inserted are locked until the logical unit of
work is committed or rolled back. A record
that is read but not updated is locked until
the completion of the SQL statement, or the
cursor is closed, or the logical unit of work
is committed or rolled back. Uncommitted
changes in other jobs cannot be seen.

*RR Records that are updated, deleted, and


inserted are locked until the logical unit
of work is committed or rolled back.
Uncommitted changes in other jobs cannot
be seen. All tables referred to in SELECT,
UPDATE, DELETE, and INSERT statements
are locked exclusively until the logical unit
of work is committed or rolled back.

*RREL Records that are read, updated, deleted,


and inserted are locked exclusively until
the logical unit of work is committed or
rolled back. Uncommitted changes in other
jobs cannot be seen. All tables referred to
in SELECT, UPDATE, DELETE, and INSERT
statements are locked exclusively until the
logical unit of work is committed or rolled
back.

*RSEL Records that are read, updated, deleted,


and inserted are locked exclusively until the
logical unit of work is committed or rolled
back. Uncommitted changes in other jobs
cannot be seen.

Contains the null value if the file is closed.

STATUS VARCHAR(13) File status.

CLOSED The file has been closed with


pending changes that have not been
committed or rolled back.

OPEN The file is open under commitment


control.

PSEUDO- The file has been pseudo-closed.


CLOSED This is an SQL cursor that is not
currently in use, but remains open
under commitment control for reuse
to minimize performance impacts.

Database performance and query optimization 479


Table 96. DB_TRANSACTION_RECORD_INFO table function (continued)

Column Name Data Type Description

CONCURRENT_ACCESS_RESOLUTION VARCHAR(7) The concurrent access resolution setting for this file.

*CURCMT The database manager can use the


currently committed version of the data
for applicable scans when it is in the
process of being updated or deleted.
Rows in the process of being inserted
can be skipped.

*SKIP The database manager will skip data on


which incompatible locks are held by
other transactions.

*WAIT The database manager will wait for the


commit or rollback when encountering
data in the process of being updated or
deleted. Rows encountered that are in
the process of being inserted are not
skipped.

Contains the null value if the file is closed.

JOURNAL_LIBRARY VARCHAR(10) The library that contains the journal.

JOURNAL_NAME VARCHAR(10) The journal in which changes to the file are recorded.
Can contain the following special value:

*MULTIPLE Logical files based on physical files are


not all journaled to the same journal.

COMMIT_CYCLE DECIMAL(21,0) The commit cycle identifier of the current logical unit
of work (LUW) for this file's journal. The commit cycle
identifier is the sequence number of the journal entry
that corresponds to the beginning of the current LUW
for the commitment definition.
Contains the null value if no changes have been made
to local database files under commitment control, and
no user journal entries have been sent to this journal
on behalf of an API resource that is journaled to the
file's journal during this LUW.

Example
• View all the files associated with a given commit definition.

SELECT * FROM TABLE(QSYS2.DB_TRANSACTION_RECORD_INFO('UDB_0100000000000001'));

• View all the files with pending changes for a given commit definition.

SELECT * FROM TABLE(QSYS2.DB_TRANSACTION_RECORD_INFO('UDB_0100000000000001'))


WHERE FILE_CHANGES_PENDING > 0;

ENVIRONMENT_VARIABLE_INFO view
The ENVIRONMENT_VARIABLE_INFO view contains information about environment variables.
The values returned for the columns in the view are similar to the values returned by the WRKENVVAR
CL command or Get All System-Level Environment Variables API. Refer to the API for more detailed
information.
Authorization: None required.
The following table describes the columns in the view. The system name is ENV_VARS. The schema is
QSYS2.

480 IBM i: Performance and Query Optimization


Table 97. ENVIRONMENT_VARIABLE_INFO view

Column Name System Column Name Data Type Description

ENVIRONMENT_VARIABLE_TYPE VAR_TYPE VARCHAR(6) The type of environment variable.

SYSTEM Defined as a system level


environment variable.

JOB Defined as a job level environment


variable. This variable and value only
apply to the current connection.

PASE Defined as an IBM Portable


Application Solutions Environment for
i (PASE for i) environment variable.
This variable and value only apply
to the current job. PASE variables
are not returned unless the PASE
environment has been started.

ENVIRONMENT_VARIABLE_NAME VAR_NAME VARGRAPHIC(128) CCSID The name of the environment variable. If


1200 the name is longer than 128 characters,
it will be truncated with no warning. If
ENVIRONMENT_VARIABLE_CCSID is 65535, the
content of this column is set using the job default
CCSID.

ENVIRONMENT_VARIABLE_VALUE VAR_VALUE VARGRAPHIC(1024) The current value of the environment variable.


CCSID 1200 If the value is longer than 1024 characters,
it will be truncated with no warning. If
Nullable ENVIRONMENT_VARIABLE_CCSID is 65535, the
content of this column is set using the job default
CCSID.
Contains null if there is no value.

ENVIRONMENT_VARIABLE_BINARY_NAME VAR_BNAME VARBINARY(128) The name of the environment variable in binary


form. This is the raw value for the name. If the
name is longer than 128 characters, it will be
truncated with no warning.

ENVIRONMENT_VARIABLE_BINARY_VALUE VAR_BVALUE VARBINARY(1024) The current value of the environment variable.


This is the raw value for the value. If the value is
Nullable longer than 1024 characters, it will be truncated
with no warning.
Contains null if there is no value.

ENVIRONMENT_VARIABLE_CCSID VAR_CCSID INTEGER The CCSID value associated with the environment
variable.

Example
Look at all system level environment variables and their values for this connection:

SELECT ENVIRONMENT_VARIABLE_NAME, ENVIRONMENT_VARIABLE_VALUE


FROM QSYS2.ENVIRONMENT_VARIABLE_INFO
WHERE ENVIRONMENT_VARIABLE_TYPE = 'SYSTEM'

ERRNO_INFO scalar function


The ERRNO_INFO scalar function returns descriptive text that corresponds to an errno value.
The function requires that Option 13 (System Openness Includes) of the IBM i operating system is
installed.
Authorization: See Note below.

ERRNO_INFO ( errno )
ERRNO =>

The schema is SYSTOOLS.

errno An integer representing an errno value returned from an API call.

Database performance and query optimization 481


The result of the function is VARCHAR(256). If no descriptive text for the errno is found, the null value is
returned.

Note
This function is provided in the SYSTOOLS schema as an example of how to embed a C language interface
in an SQL scalar function. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can
be extracted and used as a model for building similar helper functions, or to create a customized version
within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Return information for errno 3025.

VALUES SYSTOOLS.ERRNO_INFO(3025);

EXIT_POINT_INFO view
The EXIT_POINT_INFO view returns information about exit points.
The values returned for the columns in the view are closely related to the values returned by the
Work with Registration Information (WRKREGINF) CL command and by the Retrieve Exit Information
(QUSRTVEI, QusRetrieveExitInformation) API.
Authorization: None required.
The following table describes the columns in the view. The system name is EXIT_POINT. The schema is
QSYS2.
Table 98. EXIT_POINT_INFO view

Column Name System Column Name Data Type Description

EXIT_POINT_NAME EXIT_NAME VARCHAR(20) The name of the exit point.

EXIT_POINT_FORMAT EXIT_FMT CHAR(8) The format name associated with the


exit point.

REGISTERED REGISTERED VARCHAR(3) Whether the exit point is registered


with the registration facility.

NO The exit point is


unregistered.

YES The exit point is registered.

ALLOW_DEREGISTRATION DEREGISTER VARCHAR(3) Whether the exit point can be


deregistered.

NO The exit point cannot be


deregistered.

YES The exit point can be


deregistered.

ALLOW_CHANGE CHANGE VARCHAR(3) Whether the exit point controls can


be changed.

NO The exit point controls


cannot be changed.

YES The exit point controls can


be changed.

EXIT_PROGRAMS EXIT_PGMS INTEGER The current number of exit programs


associated with the exit point.

482 IBM i: Performance and Query Optimization


Table 98. EXIT_POINT_INFO view (continued)

Column Name System Column Name Data Type Description

MAXIMUM_EXIT_PROGRAMS MAX_PGMS INTEGER The maximum number of exit


programs that the exit point allows.
Nullable
Contains the null value if the
maximum number of exit programs
is *NOMAX.

TEXT_DESCRIPTION TEXT VARCHAR(132) The descriptive text for the exit point.

Nullable Contains the null value if no


descriptive text is available.

ADD_EXIT_PROGRAM_LIBRARY ADD_LIB VARCHAR(10) The library in which


ADD_EXIT_PROGRAM resides.
Nullable
Contains the null value if no add exit
program is defined.

ADD_EXIT_PROGRAM ADD_PGM VARCHAR(10) The preprocessing exit program


name that is called by the
Nullable registration facility when the Add Exit
Program API is called for the exit
point.
Contains the null value if no add exit
program is defined.

ADD_EXIT_PROGRAM_FORMAT ADD_FMT CHAR(8) The format name for


ADD_EXIT_PROGRAM.
Nullable
Contains the null value if no add exit
program is defined.

REMOVE_EXIT_PROGRAM_LIBRARY RMV_LIB VARCHAR(10) The library in which


REMOVE_EXIT_PROGRAM resides.
Nullable
Contains the null value if no remove
exit program is defined.

REMOVE_EXIT_PROGRAM RMV_PGM VARCHAR(10) The preprocessing exit program


name that is called by the
Nullable registration facility when the Remove
Exit Program API is called for the exit
point.
Contains the null value if no remove
exit program is defined.

REMOVE_EXIT_PROGRAM_FORMAT RMV_FMT CHAR(8) The format name for


REMOVE_EXIT_PROGRAM.
Nullable
Contains the null value if no remove
exit program is defined.

RETRIEVE_EXIT_PROGRAM_LIBRARY RTV_LIB VARCHAR(10) The library in which


RETRIEVE_EXIT_PROGRAM resides.
Nullable
Contains the null value if no retrieve
exit program is defined.

RETRIEVE_EXIT_PROGRAM RTV_PGM VARCHAR(10) The preprocessing exit program


name that is called by the
Nullable registration facility when the Retrieve
Exit Information API is called for the
exit point.
Contains the null value if no retrieve
exit program is defined.

RETRIEVE_EXIT_PROGRAM_FORMAT RTV_FMT CHAR(8) The format name for


RETRIEVE_EXIT_PROGRAM.
Nullable
Contains the null value if no retrieve
exit program is defined.

Example
• List all the security exit points.

Database performance and query optimization 483


SELECT *
FROM QSYS2.EXIT_POINT_INFO
WHERE EXIT_POINT_NAME LIKE 'QIBM_QSY%';

EXIT_PROGRAM_INFO view
The EXIT_PROGRAM_INFO view returns information about exit programs.
The values returned for the columns in the view are closely related to the values returned by the
Work with Registration Information (WRKREGINF) CL command and by the Retrieve Exit Information
(QUSRTVEI, QusRetrieveExitInformation) API.
Authorization: None required.
The following table describes the columns in the view. The system name is EXIT_PGM. The schema is
QSYS2.
Table 99. EXIT_PROGRAM_INFO view

Column Name System Column Name Data Type Description

EXIT_POINT_NAME EXIT_NAME VARCHAR(20) The exit point name.

EXIT_POINT_FORMAT EXIT_FMT CHAR(8) The exit point format name associated with the
exit point.

REGISTERED REGISTERED VARCHAR(3) Whether the exit point is registered with the
registration facility.

NO The exit point is unregistered.

YES The exit point is registered.

COMPLETE COMPLETE VARCHAR(3) Whether the information returned for the exit
point is complete and accurate. Incomplete
information may occur when the exit point's
retrieve preprocessing program indicates that
the information it returned is incomplete or
inaccurate.

NO The exit point entry information is not


complete or accurate. The remaining
columns should be ignored.

YES The exit point entry information is


complete and accurate.

EXIT_PROGRAM_NUMBER NUMBER INTEGER The exit program number associated with the exit
program. This number determines the processing
sequence of exit programs associated with an exit
point, where the lowest number is processed first.

EXIT_PROGRAM_LIBRARY LIBRARY VARCHAR(10) The library in which EXIT_PROGRAM resides.

EXIT_PROGRAM PROGRAM VARCHAR(10) The name of the exit program.

TEXT_DESCRIPTION TEXT VARCHAR(132) The descriptive text for the exit program .

Nullable Contains the null value if no descriptive text is


available.

EXIT_PROGRAM_DATA DATA VARCHAR(2048) The data that is associated with the exit program.

Nullable Contains the null value when there is no exit


program data.

EXIT_PROGRAM_DATA_CCSID DATA_CCSID INTEGER The coded character set identifier (CCSID) to use
for working with the exit program data.
Nullable
Contains the null value when
EXIT_PROGRAM_DATA is null.

THREADSAFE THREADSAFE VARCHAR(3) The thread safety status of the exit program entry.

Nullable NO The exit program entry is not threadsafe.

YES The exit program entry is threadsafe.

Contains the null value when the threadsafe


status of the exit program entry is not known.

484 IBM i: Performance and Query Optimization


Table 99. EXIT_PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

MULTITHREADED_JOB_ACTION JOB_ACTION VARCHAR(6) The action to take when calling an exit program in
a multithreaded job.

*MSG Run the exit program in the current


multithreaded job, but send an
informational message. CPI3C80
can be used as the informational
message.

*NORUN Do not run the exit program


in the current multithreaded job.
Depending on the exit point, do one
of the following:
1. Send an escape message and
do not call the exit program.
CPF3C80 can be used as the
escape message.
2. Send an informational message
and do not call the exit program.
CPF3C80 can be used as the
informational message.
3. Call the exit program in a non-
multithreaded job.

*RUN Run the exit program in the current


multithreaded job.

QMLTTHDACN_SYSTEM_VALUE QMLTTHDACN VARCHAR(3) Indicates whether the QMLTTHDACN system


value was used in determining the multithreaded
job action.

NO The QMLTTHDACN system value was not


used to determine the multithreaded job
action.

YES The QMLTTHDACN system value was


used to determine the multithreaded job
action.

Example
• List all the exit programs associated with security exit points.

SELECT *
FROM QSYS2.EXIT_PROGRAM_INFO
WHERE EXIT_POINT_NAME LIKE 'QIBM_QSY%'
ORDER BY EXIT_POINT_NAME, EXIT_PROGRAM_NUMBER;

GENERATE_SPREADSHEET scalar function


The GENERATE_SPREADSHEET scalar function generates a file in the Integrated File System containing a
spreadsheet based on either the results of a query or the complete content of a database file.
This scalar function relies upon the CLDownload feature provided by the IBM i Access Client Solutions
(ACS) jar that ships on every IBM i. The ACS jar is delivered via the IBM HTTP SERVER FOR i PTF Group,
and is found at this path: /QIBM/proddata/Access/ACS/Base/acsbundle.jar
CLOB, BLOB, DBCLOB, and XML data is not supported by CLDownload. It can be returned by casting the
column to a non-LOB string data type.
Authorization: See Note below.

Database performance and query optimization 485


GENERATE_SPREADSHEET ( path-name
PATH_NAME =>

, spreadsheet-query
SPREADSHEET_QUERY =>

, library-name
LIBRARY_NAME =>

, file-name
FILE_NAME =>

, spreadsheet-type
SPREADSHEET_TYPE =>

)
, column-headings
COLUMN_HEADINGS =>

The schema is SYSTOOLS.

path-name A character string containing the name of the path where the result spreadsheet file
is to be written. An existing file is overwritten.
spreadsheet- A character string containing a query to run that identifies the rows to be included in
query the spreadsheet. The query can be up to 4000 characters long. Objects referenced in
the query must be fully qualified.
If this parameter is omitted, library-name and file-name must be specified.
library-name The name of the library containing file-name. QTEMP, *LIBL, and *CURLIB are not
supported.
file-name A character string containing the name of the database file that contains the rows
and columns of data to include in the spreadsheet. The file must be in SYSBASE.
If spreadsheet-query is specified, values for library-name and file-name are ignored.
spreadsheet- A character string containing the type of spreadsheet to generate. The supported
type values are csv, ods, txt, xls, and xlsx. These values must be provided in lower
case.
If this parameter is omitted, csv is used.
column-headings A character string that specifies whether a heading row is included in the
spreadsheet result.

COLUMN The column names are used as the heading.


LABEL The column labels are used as the heading. If no column label exists, the
column name is used.
NONE No heading row is returned. This is the default.

The result of the function is an integer. If the function is successful, it returns a value of 1. If the function
encounters an error, it returns a value of -1.

486 IBM i: Performance and Query Optimization


Note
This function is provided in the SYSTOOLS schema as an example of invoking a Qshell command from
within an SQL scalar function. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source
can be extracted and used as a model for building similar helper functions, or to create a customized
version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
• Create a spreadsheet that contains the data from MYLIB/A.

VALUES SYSTOOLS.GENERATE_SPREADSHEET(
PATH_NAME => '/usr/fileA_spreadsheet',
FILE_NAME => 'A',
LIBRARY_NAME => 'MYLIB');

• Create a spreadsheet that contains the data from a query. Return column names in the first row of the
spreadsheet.

VALUES SYSTOOLS.GENERATE_SPREADSHEET(
PATH_NAME => '/usr/query_spreadsheet',
SPREADSHEET_QUERY => 'select order_number, customer, balance
from orders where shipped = ''YES''',
COLUMN_HEADINGS => 'COLUMN');

GETENV scalar function


The GETENV scalar function retrieves the value of an environment variable for the current job.
The function is implemented using the getenv() API. The result is similar to the
QSYS2.ENVIRONMENT_VARIABLE_INFO view and the Work with Environment Var (WRKENVVAR) CL
command.
The function requires that Option 13 (System Openness Includes) of the IBM i operating system is
installed.
Authorization: See Note below.

GETENV ( environment-variable-name
ENVIRONMENT_VARIABLE_NAME =>

The schema is SYSTOOLS.

environment-variable-name An expression that returns the name of an environment variable.

The result of the function is a variable-length character string that contains the value of the environment
variable, from 0 to 1024 characters in length. If the environment variable is not found, the function
returns the null value.

Note
This function is provided in the SYSTOOLS schema as an example of how to embed a C interface within
SQL PL code. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can be extracted
and used as a model for building similar helper functions, or to create a customized version within a
user-specified schema.

Database performance and query optimization 487


Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
• Get the value of MY_ENVVAR for the current job.

VALUES SYSTOOLS.GETENV('MY_ENVVAR');

LPRINTF procedure
The LPRINTF procedure writes an informational message to the joblog. It is severity 0 and has no
message identifier.
Authorization: See Note below.

LPRINTF ( print-string )
PRINT_STRING =>

The schema is SYSTOOLS.

print-string A character or graphic string containing the information to be written to the joblog. It can be
up to 30,720 characters long.

Note
This procedure is provided in the SYSTOOLS schema as an example of how to write to the joblog using
an SQL procedure. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can be
extracted and used as a model for building similar procedures, or to create a customized version within a
user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Write a message to the joblog.

CALL SYSTOOLS.LPRINTF('This message sent on '


CONCAT DAYOFWEEK(CURRENT DATE) CONCAT ' at '
CONCAT CURRENT TIME);

Results in this string in the joblog:

This message sent on Saturday at 04:21 PM

PROGRAM_EXPORT_IMPORT_INFO view
The PROGRAM_EXPORT_IMPORT_INFO view returns the data and procedure that are exported or
imported for an ILE program or service program.
The values returned for the columns in the view are closely related to the values returned for *PROCEXP,
*DTAEXP, *ACTGRPEXP, and *ACTGRPIMP detail on the DSPSRVPGM (Display Service Program) CL
command and *ACTGRPEXP and *ACTGRPIMP detail on the DSPPGM (Display Program) CL command.
It is similar to the information returned by the List Service Program Information (QBNLSPGM) and List
Program Information (QBNLPGMI) APIs.
Authorization: The caller must have:

488 IBM i: Performance and Query Optimization


• *EXECUTE authority to the library containing the program or service program, and
• *READ authority to the program or service program.
The following table describes the columns in the view. The system name is EXPIMP_INF. The schema is
QSYS2.
Table 100. PROGRAM_EXPORT_IMPORT_INFO view

Column Name System Column Name Data Type Description

PROGRAM_LIBRARY PGM_LIB VARCHAR(10) The library containing the program or service


program.

PROGRAM_NAME PGM_NAME VARCHAR(10) The program or service program to which this


export or import applies.

OBJECT_TYPE OBJ_TYPE VARCHAR(7) Object type for PROGRAM_NAME.

*PGM A program.

*SRVPGM A service program.

SYMBOL_NAME NAME VARGRAPHIC(8192) The name of a procedure or data export or import.

CCSID 1200

SYMBOL_USAGE USAGE VARCHAR(10) The type of export or import.

*ACTGRPEXP The data export to the


activation group.

*ACTGRPIMP A data import that is resolved


by a weak export that had
been exported to the activation
group.

*DTAEXP A data item exported from this


service program.

*PROCEXP A procedure exported from this


service program.

ARGUMENT_OPTIMIZATION ARGOPT VARCHAR(4) Whether the service program procedure export


uses argument optimization.
Nullable
*NO The procedure export does not use
argument optimization.

*YES The procedure export uses argument


optimization.

Contains the null value if SYMBOL_USAGE is not


*PROCEXP.

DATA_ITEM_SIZE DATA_SIZE INTEGER The size of the data item export, in bytes.

Nullable Contains the null value if SYMBOL_USAGE is not


*ACTGRPEXP.

Example
• Show all the procedure exports for service program APP_PGM1 in APPLIB.

SELECT *
FROM QSYS2.PROGRAM_EXPORT_IMPORT_INFO
WHERE PROGRAM_LIBRARY = 'APPLIB' AND
PROGRAM_NAME = 'APP_PGM1' AND
OBJECT_TYPE = '*SRVPGM' AND
SYMBOL_USAGE = '*PROCEXP';

• Find the service program in QSYS that exports printf to joblog (Qp0zLprintf).

SELECT *
FROM QSYS2.PROGRAM_EXPORT_IMPORT_INFO
WHERE PROGRAM_LIBRARY = 'QSYS' AND SYMBOL_NAME = 'Qp0zLprintf';

Database performance and query optimization 489


PROGRAM_INFO view
The PROGRAM_INFO view returns information about programs.
The values returned for the columns in the view are closely related to the values returned by the
DSPPGM (Display Program) and DSPSRVPGM (Display Service Program) CL commands (the *BASIC,
*SIZE, *SIGNATURE, and *COPYRIGHT details for ILE programs and service programs) and the Retrieve
Program Information (QCLRPGMI) and Retrieve Service Program Information (QBNRSPGM) APIs.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the program or service program, and
• *READ authority to the program or service program.
The following table describes the columns in the view. The first set of columns, through
CONVERSION_DETAIL, apply to all ILE and OPM programs and service programs. The next group of
columns apply to only ILE programs and service programs. The final group of columns apply to only OPM
programs. The system name is PGM_INFO. The schema is QSYS2.
Table 101. PROGRAM_INFO view

Column Name System Column Name Data Type Description

PROGRAM_LIBRARY PGM_LIB VARCHAR(10) The library containing the program or service


program.

PROGRAM_NAME PGM_NAME VARCHAR(10) The program or service program.

PROGRAM_TYPE PGM_TYPE VARCHAR(3) The type of program or service program.

ILE An Integrated Language Environment®


program or service program.

OPM An original program model program.

OBJECT_TYPE OBJ_TYPE VARCHAR(7) Object type for PROGRAM_NAME.

*PGM A program.

*SRVPGM A service program.

CREATE_TIMESTAMP CREATE_TS TIMESTAMP(0) The timestamp when the program or service


program was created.

TEXT_DESCRIPTION TEXT VARCHAR(50) The user text, if any, used to briefly describe the
program or service program.
Nullable
Contains the null value if there is no text
description.

PROGRAM_OWNER OWNER VARCHAR(10) The name of the program or service program


owner's user profile.
Nullable
Contains the null value if no program owner is
available.

PROGRAM_ATTRIBUTE ATTRIBUTE VARCHAR(10) For an ILE program, the ILE language used for the
module containing the program entry procedure
Nullable (PEP).
For a service program, the language in which the
modules of the service program are written.
For an OPM program, the language the program is
written in.
Contains the null value is there is no attribute
value or if a service program contains modules
generated by different compilers.

490 IBM i: Performance and Query Optimization


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

USER_PROFILE USRPRF VARCHAR(6) The value specified for the USRPRF option on the
command used to create the program or service
program.

*OWNER The program or service program


runs under both the current user's
and the owner's user profiles.

*USER The program or service program


runs under the current user's user
profile.

USE_ADOPTED_AUTHORITY USEADPAUT VARCHAR(4) The value specified for the USEADPAUT option
on the command used to change the program or
service program.

*NO Does not use program adopted authority


from previous call levels when this
program or service program is running

*YES Uses program adopted authority from


previous call levels when this program
or service program is running.

PROGRAM_STATE STATE VARCHAR(8) The state of the program or service program.

*INHERIT The program or service program


runs under (inherits) the same
state as its caller.

*SYSTEM The program or service program


can call user-domain or system-
domain programs.

*USER The program or service program


can call only user-domain
programs.

PROGRAM_DOMAIN DOMAIN VARCHAR(7) The domain of the program or service program.

*SYSTEM The program or service program can


be called by system-state programs.

*USER The program can be called by user-


state or system-state programs.

EARLIEST_POSSIBLE_RELEASE EARLY_REL CHAR(6) The version, release, and modification level of the
earliest release the program or service program is
allowed to run on, in VvRrMm format. The target
release (TGTRLS) parameter of the command can
affect this value.

RELEASE_CREATED_ON CREATE_ON CHAR(6) The version, release, and modification level of the
operating system, in VvRrMm format, on which
Nullable the program or service program was created.
Contains the null value for OPM programs.

TARGET_RELEASE TGTRLS CHAR(6) This is the release specified on the target release
(TGTRLS) parameter of the command.
Nullable
Contains the null value for OPM programs.

MINIMUM_NUMBER_PARMS MIN_PARMS INTEGER The minimum number of parameters that is to be


received by the program when it is called.
Nullable
Contains the null value if this is a service program
or if the information is not available.

MAXIMUM_NUMBER_PARMS MAX_PARMS INTEGER The maximum number of parameters that may be


received by the program when it is called.
Nullable
Contains the null value if this is a service program
or if the information is not available.

ASSOCIATED_SPACE_SIZE ASSOC_SIZE INTEGER The size (in bytes) of the associated space used
by this program or service program.

Database performance and query optimization 491


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

PAGING_POOL POOL VARCHAR(8) The paging pool used for the program or service
program object.

*BASE Use the base pool.

*MACHINE Use the machine pool.

*USER Use the user pool.

PAGING_AMOUNT PAGEAMOUNT VARCHAR(8) The paging behavior for the program or service
program.

*BLOCK Page the program or service


program in multiple-page blocks.

*NOBLOCK Page the program or service


program one page at a time.

ALLOW_RTVCLSRC ALWRTVSRC VARCHAR(4) Value of the ALWRTVSRC parameter if this


program was created using the Create CL Program
Nullable (CRTCLPGM) command.

*NO Source for the CL program is not saved


with the program.

*YES Source is saved.

Contains the null value if this is not a CL program.

CONVERSION_REQUIRED CONVREQ VARCHAR(4) Indicates whether the program or service


program has been converted to the format
required by the machine or if conversion is still
required.

*NO Conversion is not required.

*YES Conversion is required.

CONVERSION_DETAIL CONVDETAIL VARCHAR(8) Indicates details about the conversion status.

*COMMON The object is compatible and


requires only features common
to all systems supported by this
release.

*COMPAT The object is compatible, but


requires features not present on
all systems supported by this
release.

*FEATURE The object is not compatible.


The format is current, but the
object requires features not
present on the current machine
implementation.

*FORMAT The object is not compatible


because it is in an older format.

The following columns apply to ILE programs and service programs. They will contain the null value for OPM programs.

PROGRAM_ENTRY_PROCEDURE_ PEP_LIB VARCHAR(10) The library name that contained the module that
MODULE_LIBRARY contained the program entry procedure for this
Nullable program when the bind was done.
Contains the null value if this is a service program.

PROGRAM_ENTRY_PROCEDURE_MODULE PEP_MODULE VARCHAR(10) The module name that contains the program
entry procedure for this program.
Nullable
Contains the null value if this is a service program.

492 IBM i: Performance and Query Optimization


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

ACTIVATION_GROUP ACTGRP VARCHAR(10) The name of the activation group in which this
program or service program runs. If the activation
Nullable group already exists when the program or service
program is called, it runs in the existing activation
group. If the activation group does not exist, a
new activation group is created and the program
or service program runs in it. Can contain the
following special values:

*CALLER The program or service program


runs in the activation group of
the calling program.

*DFTACTGRP The program uses one of


two existing activation groups
created when the process
is started. One default
activation group is reserved
for system-state programs.
The other default activation
group is reserved for user-state
programs.

*NEW A new unnamed activation


group is created when this
program is called. The program
runs in this activation group.

SHARED_ACTIVATION_GROUP SHARED_AG VARCHAR(4) Whether the program or service program runs in a


shared activation group.
Nullable
*NO The activation group is not shared.

*YES The activation group is shared.

OBSERVABLE_INFO_COMPRESSED OBS_COMP VARCHAR(4) Whether the observable information associated


with the program or service program is
Nullable compressed.

*NO The observable information is not


compressed.

*YES The observable information is


compressed.

RUNTIME_INFO_COMPRESSED RUN_COMP VARCHAR(4) Whether the run-time information associated with


the program or service program is compressed.
Nullable
*NO The run-time information is not
compressed.

*YES The run-time information is


compressed.

ALLOW_UPDATE ALWUPD VARCHAR(4) Whether the Update Program (UPDPGM) or


Update Service Program (UPDSRVPGM) command
Nullable is allowed on this program or service program.

*NO The update command cannot be run.

*YES The update command can be run.

ALLOW_BOUND_SRVPGM_LIBRARY_ ALWLIBUPD VARCHAR(4) Whether the Update Program (UPDPGM) or


UPDATE Update Service Program (UPDSRVPGM) command
Nullable is allowed to change the bound *SRVPGM library
names on this program or service program.

*NO The update command cannot specify


a library name for the SRVPGMLIB
parameter.

*YES The update command can specify


a library name for the SRVPGMLIB
parameter.

Database performance and query optimization 493


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

ALL_CREATION_DATA ALL_CREATE VARCHAR(6) Whether the program or service program has


all creation data and if that data is observable
Nullable or unobservable. All observable creation data
is needed to re-create the program or service
program using the Change Program (CHGPGM)
or Change Service Program (CHGSRVPGM)
command. All creation data (either observable or
unobservable) is needed to convert the program
or service program during restore.

*NO Not all of the creation data is


present.

*UNOBS All the creation data is present but


not all of that data is observable.

*YES All the creation data is present and


all of that data is observable.

PROFILING_DATA PRF_DATA VARCHAR(10) Specifies the profiling data attribute for this
program or service program.
Nullable
*APYALL Block order and procedure
order profiling data are applied
to this program or service
program. The collection of
profiling data is no longer
enabled.

*APYBLKORD Block order profiling data


has been applied to at least
one module bound into this
program or service program.

*APYPRCORD Procedure order profiling data


has been applied to this
program or service program.

*COL The collection of profiling


data is enabled for at least
one module bound into this
program or service program.
Any applied profiling data has
been removed.

*NOCOL The collection of profiling data


is not enabled and profiling
data is not applied.

TERASPACE_STORAGE_ENABLED_ TERA_MOD VARCHAR(5) The teraspace storage capability of the modules


MODULES bound to this program or service program.
Nullable
*ALL All modules bound to this program or
service program are teraspace storage
enabled.

*NONE No modules bound to this program or


service program are teraspace storage
enabled.

*SOME One or more modules bound to


this program or service program are
teraspace storage enabled.

TERASPACE_STORAGE_ENABLED_PEP TERA_PEP VARCHAR(4) Indicates whether the Program Entry Procedure


(PEP) is teraspace enabled.
Nullable
*NO The PEP module is not teraspace
storage enabled.

*YES The PEP module is teraspace storage


enabled.

Contains the null value if this is a service program.

494 IBM i: Performance and Query Optimization


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

STORAGE_MODEL STGMDL VARCHAR(10) Where the automatic and static storage for this
program or service program is allocated at run
Nullable time.

*INHERIT Automatic and static storage


are allocated from either single-
level storage or teraspace,
depending on the activation.

*SNGLVL Automatic and static storage


are allocated from single-level
storage.

*TERASPACE Automatic and static storage


are allocated from teraspace.

ARGUMENT_OPTIMIZATION ARGOPT VARCHAR(4) Whether argument optimization was done during


program or service program creation.
Nullable
*NO Argument optimization was not
performed.

*YES Argument optimization was performed.

NUMBER_OF_UNRESOLVED_REFERENCES UNRESOLVED INTEGER The number of symbols that could not be resolved
at Create Program (CRTPGM) or Create Service
Nullable Program (CRTSRVPGM) command time.

ALLOW_STATIC_STORAGE_REINIT ALWRINZ VARCHAR(4) Whether program or service program static


storage can be reinitialized.
Nullable
*NO Static storage cannot be reinitialized.

*YES Static storage can be reinitialized.

MINIMUM_STATIC_STORAGE_SIZE MIN_STATIC BIGINT The minimum static storage size, in bytes, that
this program or service program needs in order to
Nullable run.

MAXIMUM_STATIC_STORAGE_SIZE MAX_STATIC BIGINT The maximum static storage size, in bytes, that
this program or service program may need in
Nullable order to run.

AUXILIARY_STORAGE_SEGMENTS NBR_AUX INTEGER The number of auxiliary storage segments in this


program or service program.
Nullable

MAXIMUM_AUXILIARY_STORAGE_ MAX_AUX INTEGER The maximum number of auxiliary storage


SEGMENTS segments an ILE program or service program can
Nullable have.

PROGRAM_SIZE PGM_SIZE INTEGER The total size of the program or service program,
in kilobytes.
Nullable

MAXIMUM_PROGRAM_SIZE MAXPGMSIZE INTEGER The maximum size that an ILE program or service
program can be, in kilobytes.
Nullable

MODULES MODULES INTEGER The number of modules bound into this program
or service program.
Nullable

MAXIMUM_MODULES MAXMODS INTEGER The maximum number of modules that can be


bound into an ILE program or service program.
Nullable

SERVICE_PROGRAMS SRVPGMS INTEGER The number of service programs bound to this


program or service program.
Nullable

MAXIMUM_SERVICE_PROGRAMS MAXSRVPGMS INTEGER The maximum number of service programs that


can be bound to an ILE program or service
Nullable program.

STRING_DIRECTORY_SIZE STRDIRSIZE INTEGER The program or service program's string directory


size.
Nullable

Database performance and query optimization 495


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

MAXIMUM_STRING_DIRECTORY_SIZE MAXSTRDIR INTEGER The maximum size that the string directory can be
in an ILE program or service program.
Nullable

COPYRIGHTS COPYRIGHTS INTEGER The number of copyrights in this program or


service program.
Nullable

COPYRIGHT_STRINGS COPYR_JSON CLOB(16M) A list of copyrights. The value is returned


as an array within a JSON object. It
CCSID 1208 is formatted as: {"COPYRIGHT":["first-
Nullable string", "second-string",...]}

Contains the null value if COPYRIGHTS is 0.

COPYRIGHT_STRING_SIZE CPYRSTRSIZ INTEGER The program or service program's copyright string


size.
Nullable

MAXIMUM_COPYRIGHT_STRING_SIZE MAXCPYRSTR INTEGER The maximum size of the copyright string in an


ILE program or service program.
Nullable

EXPORT_SOURCE_LIBRARY EXP_SRCLIB VARCHAR(10) The name of the library that contains the export
source file. Can contain the following special
Nullable value:

*LIBL The library list.

Contains the null value if EXPORT_SOURCE_FILE


is null.

EXPORT_SOURCE_FILE EXP_SRCF VARCHAR(10) The name of the export source file that contains
the export source file member.
Nullable
Contains the null value if this is not a service
program, if there is no export source, if the export
source was not specified using a source file, or if
you are not authorized to this information.

EXPORT_SOURCE_FILE_MEMBER EXP_SRCM VARCHAR(10) The name of the member in the export source file
that was used to create this service program.
Nullable
Contains the null value if EXPORT_SOURCE_FILE
is null.

EXPORT_SOURCE_STREAM_FILE EXP_STMF VARGRAPHIC(5000) The path name of the stream file that contains the
CCSID 1200 export source for this service program.

Nullable Contains the null value if this is not a service


program or if the export source was not specified
using a stream file.

PROCEDURE_EXPORTS PROCEXP INTEGER The number of procedures exported from this


service program.
Nullable
Contains the null value if this is not a service
program.

MAXIMUM_PROCEDURE_EXPORTS MAXPROCEXP INTEGER The maximum number of procedures that can be


exported by a service program.
Nullable
Contains the null value if this is not a service
program.

DATA_EXPORTS DATAEXP INTEGER The number of data items exported from this
service program.
Nullable
Contains the null value if this is not a service
program.

MAXIMUM_DATA_EXPORTS MAXDATAEXP INTEGER The maximum number of data items that can be
exported by a service program.
Nullable
Contains the null value if this is not a service
program.

SIGNATURES SIGNATURES INTEGER The number of signatures for this service


program. This is the number of entries returned
Nullable in EXPORT_SIGNATURES.
Contains the null value if this is not a service
program.

496 IBM i: Performance and Query Optimization


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

EXPORT_SIGNATURES EXP_SIG BLOB(557038) The list of export signatures for this service
program. Each signature is a binary string with a
Nullable length of 16. A single hexadecimal 00 character
separates values.
The current export signature of this service
program is the first one in the list.
Contains the null value if this is not a service
program.

MAXIMUM_SIGNATURES MAXSIGS INTEGER The maximum number of signatures that can be


in a service program.
Nullable
Contains the null value if this is not a service
program.

The following columns apply to OPM programs. They will contain the null value for ILE programs and service programs.

SOURCE_FILE_LIBRARY SRCLIB VARCHAR(10) The name of the library that contains the source
file used to create the program..
Nullable
Contains the null value if no source file was used
to create the program.

SOURCE_FILE SRCFILE VARCHAR(10) The name of the source file used to create the
program.
Nullable
Contains the null value if no source file was used
to create the program.

SOURCE_FILE_MEMBER SRCMBR VARCHAR(10) The name of the member in the source file.

Nullable Contains the null value if no source file was used


to create the program.

SOURCE_FILE_CHANGE_ SRCF_CHGTS TIMESTAMP(0) The timestamp of when the member in the source
TIMESTAMP file was last updated.
Nullable
Contains the null value if no source file was used
to create the program.

SORT_SEQUENCE_LIBRARY SRTSEQ_LIB VARCHAR(10) The name of the library that contained the sort
sequence table used when the module was
Nullable compiled. This does not apply to SQL statements
in the module. Can contain the following special
values:

*LIBL The sort sequence table is


found in the library list when
PROGRAM_NAME runs this module.

*CURLIB The sort sequence table is found


in the current library when
PROGRAM_NAME runs this module.

Contains the null value if SORT_SEQUENCE


contains a special value or is null.

SORT_SEQUENCE SRTSEQ VARCHAR(10) The name of the sort sequence table used when
the program was compiled. This does not apply to
Nullable SQL statements in the program. Can contain the
following special values:

*HEX No sort sequence is used.

*JOBRUN The sort sequence value


associated with the job at the
time the program runs.

*LANGIDSHR The shared sort sequence for


the language identifier is used.

*LANGIDUNQ The unique sort sequence for


the language identifier is used.

Contains the null value if the program does not


contain any sort sequence information.

Database performance and query optimization 497


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

LANGUAGE_ID LANGID VARCHAR(7) The language identifier used when the program
was compiled. This does not apply to SQL
Nullable statements in the program. Can contain the
following special value:

*JOBRUN The language identifier associated


with the job at the time the program
is run.

Contains the null value if the program does not


contain any language identification information.

OBSERVABLE OBSERVABLE VARCHAR(6) Whether the OPM program contains creation data
and if that data is observable or unobservable. All
Nullable observable creation data is needed to re-create
the program using CHGPGM. All creation data
(either observable or unobservable) is needed to
convert the program during restore.

*ALL The program has all creation data


and that data is observable.

*NONE The program does not have all


creation data.

*UNOBS The program has all creation data


but not all of that data is observable.

OPTIMIZATION OPTIMIZE VARCHAR(11) Indicates what was specified on the OPTIMIZE


parameter when the program was created or
Nullable changed.

*NOOPTIMIZE *NOOPTIMIZE was specified.

*OPTIMIZE *OPTIMIZE was specified.

LOG_COMMANDS LOGCMD VARCHAR(4) The value specified for the LOG parameter of the
CRTCLPGM command.
Nullable
*JOB Logging of commands in a running CL
program depends on the status of the
job's logging flag.

*NO Commands are not logged.

*YES Commands are logged in all cases.

Contains the null value if the program is not a CL


program.

FIX_DECIMAL_DATA FIXDECDATA VARCHAR(4) Whether decimal data that is not valid is


corrected or an error is signaled.
Nullable
*NO An error is signaled to the program
without correcting the data that is not
valid.

*YES Decimal data that is not valid is


corrected.

UPDATE_PASA UPDPASA VARCHAR(10) The compiler may have allowed you to control this
attribute through the GENOPT parameter of the
Nullable command used to create the program.

*NOUPDPASA Do not update internal program


automatic storage area (PASA)
stack information.

*UPDPASA Update internal PASA stack


information.

CLEAR_PASA CLRPASA VARCHAR(10) The compiler may have allowed you to control this
attribute through the GENOPT parameter of the
Nullable command used to create the program.

*CLRPASA Clear PASA storage.

*NOCLRPASA Do not clear PASA storage.

498 IBM i: Performance and Query Optimization


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

COMPILER_ID COMPILER VARCHAR(14) The licensed program identifier, version, release,


and modification level of the compiler. The value
Nullable has a pppppppbVvRrMm format, where:

ppppppp The licensed program identifier.

b A blank character.

Vv The character V is followed by a 1-


character version number.

Rr The character R is followed by a 1-


character release level.

Mm The character M is followed by a 1-


character modification level.

TERASPACE_STORAGE_ENABLED_PROGRAM TS_PGM VARCHAR(4) The teraspace storage capability of the program.


A program must be teraspace storage enabled to
Nullable access teraspace storage.

*NO This program is not teraspace storage


enabled.

*YES This program is teraspace storage


enabled.

OPM_PROGRAM_SIZE OPMPGMSIZE INTEGER The size (in bytes) of this program.

Nullable

STATIC_STORAGE_SIZE STATIC_STG INTEGER The size (in bytes) of the static storage used by
the program.
Nullable

AUTOMATIC_STORAGE_SIZE AUTO_STG INTEGER The size (in bytes) of the automatic storage used
by this program.
Nullable

NUMBER_MI_INSTRUCTIONS MI_INSTR INTEGER The number of machine interface (MI)


instructions used by this program.
Nullable
Contains the null value if the program is not
observable.

NUMBER_MI_ODT_ENTRIES MI_ODT INTEGER The number of ODT (object definition table)


entries for the program. There is a limit of 32767
Nullable ODT entries in a program.
Contains the null value if the program is not
observable.

SQL_STATEMENT_COUNT NBRSTMTS INTEGER The number of SQL statements contained in the


program.
Nullable
Contains 0 if there are no SQL statements in the
program.

SQL_RELATIONAL_DATABASE RDB VARCHAR(18) The default relational database that was specified
on the SQL precompile. Can contain the following
Nullable special value:

*LOCAL The program can only access data on


the local system.

Contains the null value if no package was created


for the program by the SQL precompiler or if the
program does not contain SQL statements.

Database performance and query optimization 499


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

SQL_COMMITMENT_CONTROL ISOLATION VARCHAR(5) The level of commitment control that was


specified on the SQL precompile.
Nullable
*ALL Read stability.

*CHG Uncommitted read.

*CS Cursor stability.

*NONE No commit.

*RR Repeatable read.

Contains the null value if the program does not


contain SQL statements.

SQL_NAMING NAMING VARCHAR(4) The convention used for naming objects in SQL
statements.
Nullable
*SQL The SQL naming convention is used.

*SYS The system naming convention is used.

Contains the null value if the program does not


contain SQL statements.

SQL_DATE_FORMAT DATFMT VARCHAR(4) The date format attribute.

Nullable *DMY Day/month/year format (dd/mm/yy).

*EUR European format (dd.mm.yyyy).

*ISO International Standards Organization


format (yyyy-mm-dd).

*JIS Japanese Industrial Standard format


(yyyy-mm-dd).

*JUL Julian format (yy/dds).

*MDY Month/day/year format (mm/dd/yy).

*USA USA format (mm/dd/yyyy).

*YMD Year/month/day format (yy/mm/dd).

Contains the null value if the program does not


contain SQL statements.

SQL_DATE_SEPARATOR DATSEP CHAR(1) The date separator attribute.

Nullable Contains the null value if the program does not


contain SQL statements.

SQL_TIME_FORMAT TIMFMT VARCHAR(4) The time format attribute.

Nullable *EUR European format (hh.mm.ss).

*HMS Hours/minutes/seconds format


(hh:mm:ss).

*ISO International Standards Organization


format (hh.mm.ss).

*JIS Japanese Industrial Standard format


(hh.mm.ss).

*USA USA format (hh:mm a.m. or p.m.).

Contains the null value if the program does not


contain SQL statements.

SQL_TIME_SEPARATOR TIMSEP CHAR(1) The time separator attribute.

Nullable Contains the null value if the program does not


contain SQL statements.

500 IBM i: Performance and Query Optimization


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

SQL_SORT_SEQUENCE_LIBRARY SQL_SSEQLB VARCHAR(10) The name of the library that is used to locate the
SQL sort sequence table. The following special
Nullable values can be returned:

*CURLIB The SQL sort sequence table is


found by looking in the current
library.

*LIBL The SQL sort sequence table is


found by looking in the library list.

Contains the null value if SQL_SORT_SEQUENCE


contains a special value or if the program does
not contain SQL statements.

SQL_SORT_SEQUENCE SQL_SRTSEQ VARCHAR(10) The sort sequence table name specified when
the program was compiled. The following special
Nullable values can be returned:

*HEX No SQL sort sequence is used


for the SQL statements.

*JOBRUN The SQL sort sequence is the


SRTSEQ value associated with
the job at the time the SQL
statements within theprogram
are run.

*LANGIDSHR The shared SQL sort sequence


for the language identifier
(LANGID) is used for the SQL
statements.

*LANGIDUNQ The unique SQL sort sequence


for the language identifier
(LANGID) is used for the SQL
statements.

Contains the null value if the program does not


contain SQL statements.

SQL_LANGUAGE_ID SQL_LANGID VARCHAR(7) The language identifier specified when the


program was compiled. The following special
Nullable value can be returned:

*JOBRUN The language identifier is the


LANGID associated with the job at
the time the program is run.

Contains the null value if the program does not


contain SQL statements.

SQL_DEFAULT_SCHEMA DFTRDBCOL VARCHAR(10) The schema name used for unqualified names of
tables, views, indexes, and SQL packages in static
Nullable statements.
Contains the null value if there is no default
schema name or if the program does not contain
SQL statements.

SQL_PATH SQLPATH VARCHAR(3483) The list of libraries used during resolution of


functions, procedures, and data types within SQL
Nullable statements. The list is in the form of repeating
library names, each surrounded by double quotes
and separated by commas.
Contains the null value if the program does not
contain SQL statements.

Database performance and query optimization 501


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

SQL_DYNAMIC_USER_PROFILE DYNUSRPRF VARCHAR(10) The user profile used for dynamic SQL
statements. The following special values can be
Nullable returned:

*OWNER Local dynamic SQL statements


are run under the profile of
the program's owner. Distributed
dynamic SQL statements are run
under the profile of the SQL
package's owner.

*USER Local dynamic SQL statements are


run under the profile of the job
or thread. Distributed dynamic SQL
statements are run under the profile
of the application server job.

Contains the null value if the program does not


contain SQL statements.

SQL_ALLOW_COPY_DATA ALWCPYDTA VARCHAR(9) Whether a copy of the data can be used in the
implementation of an SQL query.
Nullable
*NO A copy of the data is not allowed.

*OPTIMIZE A copy of the data is allowed


whenever it might result is better
performance.

*YES A copy of the data is allowed, but


only when necessary.

Contains the null value if the program does not


contain SQL statements.

SQL_CLOSE_SQL_CURSOR CLOSQLCSR VARCHAR(10) Specifies the CLOSQLCSR attribute.

Nullable *ENDJOB SQL cursors remain open between


calls and can be fetched without
running another OPEN statement.
The programs higher on the call
stack do not need to have run SQL
statements. SQL cursors are left
open, SQL prepared statements
are preserved, and LOCK TABLE
locks are held when the first
SQL program on the call stack
ends. SQL cursors are closed,
SQL prepared statements are
discarded, and LOCK TABLE locks
are released when the job ends.

*ENDPGM SQL cursors are closed and SQL


prepared statements are discarded
when the program ends. LOCK
TABLE locks are released when the
first SQL program on the call stack
ends.

*ENDSQL SQL cursors remain open between


calls and rows can be fetched
without running another OPEN
statement. One of the programs
higher on the call stack must have
run at least one SQL statement.
The SQL cursors are closed,
SQL prepared statements are
discarded, and LOCK TABLE locks
are released when the first SQL
program on the call stack ends. If
you specify *ENDSQL for a program
that is the first SQL program called
(the first SQL program on the call
stack), the program is treated as if
*ENDPGM was specified.

Contains the null value if the program does not


contain SQL statements.

502 IBM i: Performance and Query Optimization


Table 101. PROGRAM_INFO view (continued)

Column Name System Column Name Data Type Description

SQL_DELAY_PREPARE DLYPRP VARCHAR(4) Indicates the delay prepare attribute.

Nullable *NO Dynamic statement validation is


performed when the dynamic
statements are prepared.

*YES Dynamic statement validation is delayed


until the dynamic statements are used.

Contains the null value if the program does not


contain SQL statements.

SQL_ALLOW_BLOCK ALWBLK VARCHAR(8) Whether blocking is used to improve the


performance of certain SQL statements.
Nullable
*ALLREAD Rows are blocked for read-only
cursors.

*NONE Rows are not blocked for retrieval


of data for cursors.

*READ Rows are blocked for read-only


retrieval of data for cursors when:
• The commitment control value
is *NONE.
• The cursor is declared with a
FOR READ ONLY clause or there
are no dynamic statements that
could run a positioned UPDATE
or DELETE statement for the
cursor.

Contains the null value if the program does not


contain SQL statements.

SQL_PACKAGE_LIBRARY SQLPKGLIB VARCHAR(10) The name of the library the SQL package is in.

Nullable Contains the null value if the program is not


distributed or if the program does not contain SQL
statements.

SQL_PACKAGE SQLPKG VARCHAR(10) The name of the SQL package created on


the relational database specified on the RDB
Nullable parameter of the command that created this
program.
Contains the null value if the program is
not distributed or if it does not contain SQL
statements.

SQL_RDB_CONNECTION_METHOD RDBCNNMTH VARCHAR(4) Specifies the semantics used for CONNECT


statements:
Nullable
*DUW CONNECT (Type 2) semantics are used
to support distributed unit of work.

*RUW CONNECT (Type 1) semantics are used


to support remote unit of work

Contains the null value if the program is


not distributed or if it does not contain SQL
statements.

Examples
• Summarize the activation group usage for all ILE programs in APPLIB.

SELECT ACTIVATION_GROUP, COUNT(*) AS ACTIVATION_GROUP_NAME_COUNT


FROM QSYS2.PROGRAM_INFO
WHERE PROGRAM_LIBRARY = 'APPLIB'
AND PROGRAM_TYPE = 'ILE'
GROUP BY ACTIVATION_GROUP
ORDER BY 2 DESC;

• Examine the ownership of programs and service programs in APPLIB.

Database performance and query optimization 503


SELECT PROGRAM_OWNER, OBJECT_TYPE, COUNT(*) AS APPLICATON_OWNER_COUNT
FROM QSYS2.PROGRAM_INFO
WHERE PROGRAM_LIBRARY = 'APPLIB'
GROUP BY PROGRAM_OWNER, OBJECT_TYPE
ORDER BY 2, 3 DESC;

• List all the copyrights for ILE programs in APPLIB.

SELECT PROGRAM_LIBRARY, PROGRAM_NAME, PROGRAM_TYPE, COPYRIGHT


FROM QSYS2.PROGRAM_INFO,
JSON_TABLE(COPYRIGHT_STRINGS, 'lax $.COPYRIGHTS'
COLUMNS (COPYRIGHT VARCHAR(500) PATH 'lax $[*]' ))
WHERE PROGRAM_LIBRARY = 'APPLIB';

PUTENV scalar function


The PUTENV scalar function changes the value of an environment variable for the current job.
The function is implemented using the putenv() API. The result is similar to using the Add Environment
Variable (ADDENVVAR) or Change Environment Variable (CHGENVVAR) CL commands.
The function requires that Option 13 (System Openness Includes) of the IBM i operating system is
installed.
Authorization: See Note below.

PUTENV ( environment-variable-name
ENVIRONMENT_VARIABLE_NAME =>

, environment-variable-value )
ENVIRONMENT_VARIABLE_VALUE =>

The schema is SYSTOOLS.

environment-variable- An expression that returns the name of an environment variable. If it does


name not exist, it will be created.
environment-variable- An expression that returns the value to assign to environment-variable-
value name.

The result of the function is an integer. The function returns the following values:
0 The operation was successful.
non-zero The operation failed. The return value corresponds to the errno value from the API which
describes the failure.

Note
This function is provided in the SYSTOOLS schema as an example of how to embed a C interface within
SQL PL code. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can be extracted
and used as a model for building similar helper functions, or to create a customized version within a
user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
• Set the value of MY_ENVVAR for the current job.

VALUES SYSTOOLS.PUTENV('MY_ENVVAR', 'My job''s value for the environment variable');

504 IBM i: Performance and Query Optimization


QCMDEXC procedure
The QCMDEXC procedure executes a CL command.
Authorization: Any authority requirements for the CL command apply to the use of this function.

QCMDEXC ( CL-command-string )

The schema is QSYS2.

CL-command-string A character string expression containing a CL command.

The CL-command-string will be run as a CL command.

Examples
• Add a library to the library list.

CALL QSYS2.QCMDEXC('ADDLIBLE PRODLIB2');

• Add a library to the library list using an expression.

DECLARE V_LIBRARY_NAME VARCHAR(10);


SET V_LIBRARY_NAME = 'PRODLIB2';
CALL QSYS2/QCMDEXC('ADDLIBLE ' CONCAT V_LIBRARY_NAME);

QCMDEXC scalar function


The QCMDEXC scalar function executes a CL command.
Authorization: Any authority requirements for the CL command apply to the use of this function.

QCMDEXC ( command )
COMMAND =>

The schema is QSYS2.

command A character string containing a CL command. The maximum length is 32000 characters.
The result of the function is an integer. If the command is successful, the function returns a value of 1. If
the command execution fails, the function returns a value of -1.

Example
Hold any jobs that started running an SQL statement more than 2 hours ago.

SELECT JOB_NAME,
CASE WHEN QSYS2.QCMDEXC('HLDJOB ' CONCAT JOB_NAME) = 1 THEN 'Job Held'
ELSE 'Job not held'
END AS HLDJOB_RESULT
FROM TABLE (QSYS2.ACTIVE_JOB_INFO (DETAILED_INFO=> 'ALL'))
WHERE SQL_STATEMENT_START_TIMESTAMP < CURRENT TIMESTAMP - 2 HOURS;

RECEIVE_DATA_QUEUE table function


The RECEIVE_DATA_QUEUE table function returns a message from the specified data queue. The
message data is returned as character, UTF-8, and binary data.
The MESSAGE_DATA, MESSAGE_DATA_UTF8, and MESSAGE_DATA_BINARY columns contain identical
values. It is up to the user to determine which data type is most appropriate for working with the result of
the receive data queue operation.

Database performance and query optimization 505


The values returned for the result columns of the table function are closely related to the values returned
by the Receive Data Queue (QRCVDTAQ) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the data queue, and
• *OBJOPR and *READ authority to the data queue.

RECEIVE_DATA_QUEUE ( data-queue
DATA_QUEUE =>

, data-queue-library
DATA_QUEUE_LIBRARY =>

, remove
REMOVE =>

, wait-time
WAIT_TIME =>

, key-data
KEY_DATA =>

)
, key-order
KEY_ORDER =>

The schema is QSYS2.

data- A character or graphic string containing the name of the data queue.
queue
data- A character or graphic string containing the name of the library containing the data queue.
queue- Can be one of the following special values:
library
*CURLIB The job's current library is used.
*LIBL The library list is used. This is the default.

remove A character or graphic string indicating whether the message is to be removed from the data
queue after it is received.

NO The message is not removed from the data queue.


YES The message is removed from the data queue. This is the default.

wait-time The amount of time to wait, in seconds and milliseconds, if no entries exist on the data
queue. The value can be from -99999 to 99999.000.
• Any value less than zero indicates to wait forever.
• A value of zero means to continue processing immediately. This is the default.
• A positive value indicates the length of time to wait. The milliseconds part of the time is
ignored for any value over 100 and for DDM data queues.

506 IBM i: Performance and Query Optimization


key-data A character string containing the data to use as the key for receiving a message from the
data queue. This parameter is required for a keyed data queue. It must not be specified for a
non-keyed data queue.
The length of key-data must be the length specified on the KEYLEN parameter
on the Create Data Queue (CRTDTAQ) command. The KEY_LENGTH column of the
QSYS2.DATA_QUEUE_INFO view contains this value.
When this parameter is specified, key-order must also be specified.
key-order The comparison criteria between the keys of messages on the data queue and the key-data
parameter. When the system searches for the requested key, the entries are searched in
ascending order from the lowest value key to the highest value key until a match is found. If
there are entries with duplicate keys, the entry that was put on the queue first is received.
Valid values are:

EQ Equal
GE Greater than or equal
GT Greater than
LE Less than or equal
LT Less than
NE Not equal

This parameter is ignored if key-data is not specified.

The result of the function is a table containing one row or no rows with the format shown in the following
table. All the columns are nullable.
Table 102. RECEIVE_DATA_QUEUE table function

Column Name Data Type Description

MESSAGE_DATA CLOB(64512) The message received from the data queue as character data.

MESSAGE_DATA_UTF8 CLOB(64512) CCSID The message received from the data queue represented as character data in
1208 CCSID 1208.

MESSAGE_DATA_BINARY BLOB(64512) The message received from the data queue in binary form. This is the raw form of
the data.

KEY_DATA VARCHAR(256) For a keyed data queue. the key value of the returned message. This is the actual
key value, which could be different than the key-data parameter value.
Contains the null value if this is not a keyed data queue.

SENDER_JOB_NAME VARCHAR(28) The qualified job name of the sender.


Contains the null value if no sender information is available for the message.

SENDER_CURRENT_USER VARCHAR(10) The current user profile of the sender.


Contains the null value if no sender information is available for the message.

Example
Get the message from data queue DQ1 in TESTLIB with key 456.

SELECT * FROM TABLE(QSYS2.RECEIVE_DATA_QUEUE(


DATA_QUEUE => 'DQ1',
DATA_QUEUE_LIBRARY => 'TESTLIB',
KEY_DATA => '456',
KEY_ORDER => 'EQ'));

Database performance and query optimization 507


REMOVE_USER_INDEX_ENTRY and REMOVE_USER_INDEX_ENTRY_BINARY
table functions
The REMOVE_USER_INDEX_ENTRY and REMOVE_USER_INDEX_ENTRY_BINARY table functions remove
one or more entries from a user index (*USRIDX).
The values used by the table functions are closely related to the values handled by the Remove User
Index Entries (QUSRMVUI) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the user index, and
• *CHANGE authority to the user index.

REMOVE_USER_INDEX_ENTRY ( user-index

REMOVE_USER_INDEX_ENTRY_BINARY USER_INDEX =>

, user-index-library
USER_INDEX_LIBRARY =>

, operation
OPERATION =>

, remove-value
REMOVE_VALUE =>

, remove-value-end
REMOVE_VALUE_END =>

)
, max-remove
MAX_REMOVE =>

The schema is QSYS2.

user-index A character string containing the name of the user index for the removal of entries.
user-index- A character string containing the name of the library where the user index is located. Can
library be one of the following special values:

*CURLIB The current library is used.


*LIBL The library list is used.

operation The operation to be used for comparing remove-value and remove-value-end and the index
value.
If the index is keyed, the complete entry consists of the key followed by the entry
data. If the length of remove-value is less than or equal to the length of the key, the
comparison only applies to the key. If the length of remove-value is greater than the key,
the comparison will include some or all of the entry data as well.
If the index is not keyed, the comparison applies to the value of the entry data.

EQ Remove entries that match remove-value or start with remove-value.


GE Remove entries that are greater than or equal to remove-value.
GT Remove entries that are greater than remove-value.

508 IBM i: Performance and Query Optimization


LE Remove entries that are less than or equal to remove-value.
LT Remove entries that are less than remove-value.
BETWEEN Remove entries that are greater than or equal to remove-value and less than
or equal to remove-value-end.
FIRST Remove the first n entries from the user index, where n is the max-remove
value. If max-remove is not specified, all index entries are removed.
remove-value and remove-value-end are ignored.
LAST Remove the last n entries from the user index, where n is the max-remove
value. If max-remove is not specified, all index entries are removed.
remove-value and remove-value-end are ignored.

remove- A string that specifies the value to compare with the index value to determine whether an
value index entry is to be removed.
• For REMOVE_USER_INDEX_ENTRY, the input value will be converted to a character string
using the job CCSID.
• For REMOVE_USER_INDEX_ENTRY_BINARY, the input value will be considered a binary
string.
This parameter is ignored when operation is FIRST or LAST. It is required for all other
operation values.
remove- A string that specifies the value to compare with the index value as the upper bound for
value-end BETWEEN. The lengths of remove-value and remove-value-end must be the same.
• For REMOVE_USER_INDEX_ENTRY, the input value will be converted to a character string
using the job CCSID.
• For REMOVE_USER_INDEX_ENTRY_BINARY, the input value will be considered a binary
string.
This parameter is ignored when operation is not BETWEEN. It is required when operation is
BETWEEN.
max- An integer value that specifies the maximum number of user index entries satisfying the
remove remove comparison that should be removed. A value of -1 can be used to remove all index
entries that satisfy the remove comparison. The default is -1.

The result of the function is a table containing one row for each index entry that was removed with the
format shown in the following table. All columns are nullable.
Table 103. REMOVE_USER_INDEX_ENTRY table function

Column Name Data Type Description

ORDINAL_POSITION INTEGER The relative position of this row in the set of removed index entries.

USER_INDEX_LIBRARY VARCHAR(10) The name of the library where the user index was found.

USER_INDEX VARCHAR(10) The name of the user index.

REMOVED_ENTRY VARCHAR(2000) The data for the index entry that was removed, in character form. The
value includes both the key and the entry data.

REMOVED_ENTRY_BINARY VARBINARY(2000) The data for the index entry that was removed, in binary form. This is
the raw bytes of data. The value includes both the key and the entry
data.

Example
• Remove all index entries with a key value less than '00173'.

SELECT * FROM TABLE(QSYS2.REMOVE_USER_INDEX_ENTRY(USER_INDEX => 'USRIX1',


USER_INDEX_LIBRARY => 'APPLIB',

Database performance and query optimization 509


OPERATION => 'LT',
REMOVE_VALUE => '00173'));

SEND_DATA_QUEUE, SEND_DATA_QUEUE_BINARY, and


SEND_DATA_QUEUE_UTF8 procedures
The SEND_DATA_QUEUE, SEND_DATA_QUEUE_BINARY, and SEND_DATA_QUEUE_UTF8 procedures send
a message to the specified data queue. The message data can be sent as character, UTF-8, or binary data.
This procedure provides function similar to the Send Data Queue (QSNDDTAQ) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the data queue, and
• *OBJOPR and *ADD authority to the data queue.

SEND_DATA_QUEUE ( message-data

SEND_DATA_QUEUE_BINARY MESSAGE_DATA =>

SEND_DATA_QUEUE_UTF8

, data-queue
DATA_QUEUE =>

, data-queue-library
DATA_QUEUE_LIBRARY =>

, key-data
KEY_DATA =>

)
, asynchronous
ASYNCHRONOUS =>

The schema is QSYS2.

message-data The data to send to the message queue. The string can be up to 64512 characters
long.
• For SEND_DATA_QUEUE, the input value will be converted to a character string with
the job CCSID.
• For SEND_DATA_QUEUE_BINARY, the input value will be converted to a binary
string.
• For SEND_DATA_QUEUE_UTF8, the input value will be converted to a UTF-8 string.

data-queue A character or graphic string containing the name of the data queue.
data-queue- A character or graphic string containing the name of the library containing the data
library queue. Can be one of the following special values:

*CURLIB The job's current library is used.


*LIBL The library list is used. This is the default.

key-data A character string containing the key data to send to the data queue. This parameter
is required for a keyed data queue. It must not be specified for a non-keyed data
queue.

510 IBM i: Performance and Query Optimization


The length of the key must match the length specified on the KEYLEN parameter on
the Create Data Queue (CRTDTAQ) command.
asynchronous Indicates whether the send request to a DDM data queue should be processed
asynchronously. Valid values are:

NO The request should not be processed asynchronously. This is the default.


YES The request should be processed asynchronously. This can only be specified
for a DDM data queue.
If an error occurs during an asynchronous operation, the error will not be
detected until the next time the data queue is accessed synchronously.

Example
Send a message to data queue DQ1 in TESTLIB with key 456.

CALL QSYS2.SEND_DATA_QUEUE(MESSAGE_DATA => 'This is the message data',


DATA_QUEUE => 'DQ1',
DATA_QUEUE_LIBRARY => 'TESTLIB',
KEY_DATA => '456');

SEND_EMAIL scalar function


The SEND_EMAIL scalar function sends an email to a one or more recipients. This is done by using the
SNDSMTPEMM (Send SMTP E-mail Message) CL command.
This function assumes that the user invoking this function has been registered to the SMTP server by
using the ADDUSRSMTP (Add User SMTP) CL command. If the SMTP server is not active, this function will
attempt to start it before sending the email.
Authorization: See Note below.

SEND_EMAIL ( to-email
TO_EMAIL =>

, subject , body
SUBJECT => BODY =>

, attachment
ATTACHMENT =>

, cc-email
CC_EMAIL =>

)
, bcc-email
BCC_EMAIL =>

The schema is SYSTOOLS.

to-email A character string containing one or more email addresses. Addresses must be separated
by a comma. Blanks included before or after each comma are ignored.
The total number of email addresses provided with the to-email, cc-email, and bcc-email
parameters cannot exceed 20.
subject A character string up to 255 characters long containing the subject of the email.

Database performance and query optimization 511


body A character string up to 5000 characters long containing the body of the email.
attachment A character string containing up to 10 path names of integrated file system files to be sent
as attachments to the email. Each absolute path name can be up to 200 characters long.
Path names must be separated by a comma. Blanks included before or after each comma
are ignored.
If this parameter is omitted, no attachment is sent with the email.
cc-email A character string containing one or more email addresses to be included in the carbon
copy list. Addresses must be separated by a comma. Blanks included before or after each
comma are ignored.
The total number of email addresses provided with the to-email, cc-email, and bcc-email
parameters cannot exceed 20.
bcc-email A character string containing one or more email addresses to be included in the blind
carbon copy list. Addresses must be separated by a comma. Blanks included before or after
each comma are ignored.
The total number of email addresses provided with the to-email, cc-email, and bcc-email
parameters cannot exceed 20.

The result of the function is an integer. If the command is successful, the function returns a value of 1. If
the command returns an error, the function returns a value of -1.

Note
This function is provided in the SYSTOOLS schema as an example of how send an email using the
SNDSMTPEMM CL command in an SQL scalar function. Similar to other Db2 for i provided tools within
SYSTOOLS, the SQL source can be extracted and used as a model for building similar helper functions, or
to create a customized version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Examples
• Send an email to a user with an attachment.

VALUES SYSTOOLS.SEND_EMAIL(TO_EMAIL => '[email protected]',


SUBJECT => 'Status for last week',
BODY => 'Attached is the status information for last
week.',
ATTACHMENT => '/home/myuser/status.log');

• Send an email to multiple users with 2 attachments.

VALUES SYSTOOLS.SEND_EMAIL(TO_EMAIL => '[email protected], [email protected]',


CC_EMAIL => '[email protected]',
SUBJECT => 'Status and future plans',
BODY => 'Attached is the status for last week and the
future plan.',
ATTACHMENT => '/home/myuser/status.log, /home/myuser/plan.docx');

SERVICES_INFO table
The SERVICES_INFO table returns information about system-supplied services.
Authorization: The caller must have:
• *EXECUTE authority to QSYS2, and
• *OBJOPR and *READ authority to the QSYS2/SERV_INFO file.

512 IBM i: Performance and Query Optimization


The following table describes the columns in the table. The system name is SERV_INFO. The schema is
QSYS2.
Table 104. SERVICES_INFO table

System Column
Column Name Name Data Type Description

SERVICE_CATEGORY CATEGORY VARCHAR(40) Classification of the service.


• APPLICATION
• BACKUP AND RECOVERY
• COMMUNICATION
• CONFIGURATION
• DATABASE-APPLICATION
• DATABASE-PERFORMANCE
• DATABASE-PLAN CACHE
• DATABASE-UTILITY
• IFS
• JAVA
• JOURNAL
• LIBRARIAN
• MESSAGE HANDLING
• MIRROR-COMMUNICATION
• MIRROR-PRODUCT
• MIRROR-RECLONE
• MIRROR-REPLICATION
• MIRROR-RESYNCHRONIZATION
• MIRROR-SERVICEABILITY
• PERFORMANCE
• PRODUCT
• PTF
• SECURITY
• SPOOL
• STORAGE
• SYSTEM HEALTH
• WORK MANAGEMENT

SERVICE_SCHEMA_NAME SYS_NAME VARCHAR(128) Name of the schema containing the service.

SERVICE_NAME SERVNAME VARCHAR(128) Name of the service.

SQL_OBJECT_TYPE SQLTYPE VARCHAR(15) The type of object.


• GLOBAL VARIABLE
• PROCEDURE
• SCALAR FUNCTION
• TABLE
• TABLE FUNCTION
• VIEW

OBJECT_TYPE OBJTYPE VARCHAR(7) The system object type of the service.

Nullable • *FILE
• *SRVPGM
Contains null for procedures, functions, and global variables.

SYSTEM_OBJECT_NAME SYS_ONAME VARCHAR(10) The system name of the service.

Nullable Contains null for procedures, functions, and global variables.

LATEST_DB2_GROUP_LEVEL GROUPLVL INTEGER The Db2 for i PTF Group level which most recently changed this
service.
Nullable
Contains null if the service has not been enhanced in a PTF in this
release.

Database performance and query optimization 513


Table 104. SERVICES_INFO table (continued)

System Column
Column Name Name Data Type Description

INITIAL_DB2_GROUP_LEVEL INITIALLVL INTEGER The Db2 for i PTF Group level where this service was introduced.

Nullable Contains null if this service was available in the base for this
release.

EARLIEST_POSSIBLE_RELEASE MINRLS VARCHAR(6) The earliest release, in VxRxMx format, where a version of this
service is available.

EXAMPLE EXAMPLE VARCHAR(5000) An example SQL script that uses this service.

Example
Show all the available PTF services:

SELECT * FROM QSYS2.SERVICES_INFO


WHERE SERVICE_CATEGORY = 'PTF'

Db2 PTF Group dependencies


To complement the Db2 PTF Group level information provided by the SERVICES_INFO catalog table, you
can determine the Db2 PTF Group dependency level for every static SQL statement within a module,
program, or service program. The QSYS2.SYSPROGRAMSTMTSTAT catalog contains one row for every
static SQL statement. The Db2 PTF Group dependency information is surfaced in two columns:

SQL_DB2_GROUP_LEVEL Indicates the use of SQL language features. For example, new SQL
statements or query clauses surface as dependencies upon having a
certain Db2 PTF Group level (or higher) installed before the statement
can be run.
This is an SQL syntax level and is an accurate indication of the
dependency level.

SERVICES_DB2_GROUP_LEVEL Indicates the consumption of IBM i Services. For example, queries


that reference Db2 for i provided views, functions, procedures, or
global variables can surface possible dependencies upon having a
certain Db2 PTF Group level (or higher) installed before executing the
statement. If multiple services are used within a single SQL statement,
the highest dependency level is returned.
The services that are instrumented are documented in “IBM i
Services” on page 417 and Db2 for i Services. SQL built-in functions
and built-in global variables are also tracked.
This is not an exact indication of the Db2 PTF Group that is needed.
It depends on how the service is being used in your application.
The information is provided based solely on the name of the service
and the knowledge of when the latest enhancement was added for
that service. If the name of an IBM-provided service matches an
unqualified name in an SQL statement, it will be tracked as the IBM
service. Based on the reported use of these services, you will need to
determine whether the reported Db2 PTF Group is actually required.

To check all programs in APPLIB for potential SQL syntax and IBM i Service dependencies, execute the
following query. Only programs created after the SERVICES_INFO table was introduced will report this
information.

SELECT PROGRAM_NAME, SQL_DB2_GROUP_LEVEL, SERVICES_DB2_GROUP_LEVEL


FROM QSYS2.SYSPROGRAMSTMTSTAT
WHERE PROGRAM_SCHEMA = 'APPLIB' AND

514 IBM i: Performance and Query Optimization


(SQL_DB2_GROUP_LEVEL IS NOT NULL OR
SERVICES_DB2_GROUP_LEVEL IS NOT NULL);

To see more detailed information about which services are used in a program, including the name of each
service and the Db2 PTF Group level required for the service, perform the following steps:
1. STRDBG UPDPROD(*YES)
2. Precompile your program or build your SQL procedure, function, or trigger.
• To have informational messages written to the listing, add SET OPTION OUTPUT=*PRINT to your
SQL routine or specify the OUTPUT(*PRINT) parameter on the CRTSQLxxx or RUNSQLSTM CL
commands
3. For each reference to a service, message SQL7901 will be written to the joblog and, optionally, to the
precompile listing.
If you precompile with a TGTRLS of 7.1 or later, a message will be issued for each of the earlier
releases as well with an indication of the Db2 PTF Group level that is needed on that release. If the
service is not supported for a release, message SQL795B will be issued.
This information can be used to determine whether your application contains any content that might
require a certain level of Db2 PTF Group. If you need to deploy your application to a different partition or
an earlier release, this feedback can alert you to potential dependencies.
After you have created one or more objects using the steps above, you can query your job log to see if any
messages were issued that might need to be addressed.

SELECT MESSAGE_ID, MESSAGE_TEXT


FROM TABLE(QSYS2.JOBLOG_INFO('*')) X
WHERE MESSAGE_ID IN ('SQL7901', 'SQL795B')
ORDER BY ORDINAL_POSITION;

Here is one more query to help tie this information together. It will tell you the Db2 PTF Group level that is
on a partition.

SELECT MAX(PTF_GROUP_LEVEL) AS DB2_PTF_LEVEL FROM QSYS2.GROUP_PTF_INFO


WHERE PTF_GROUP_NAME LIKE 'SF9970%' AND PTF_GROUP_STATUS = 'INSTALLED';

SET_PASE_SHELL_INFO procedure
The SET_PASE_SHELL_INFO procedure provides the ability to set the path to the PASE shell for the
specified user or the path to the default shell returned for users that do not have a configured shell.
The path set by this procedure is returned in the pw_shell field in struct pw from PASE APIs such as
Get User Information for User Name (getpwnam) and Get User Information for User ID (getpwuid). It
is also returned by the QSYS2.USER_INFO view . If a user does not have a path set, the default shell
path is returned; if the default shell is not set, an empty string is returned. The pw_shell field is used
by PASE applications that need to execute shells for a user, such as the OpenSSH server. The OpenSSH
server will start this application as the initial program when the user logs in. If it is not set it will use /
QOpenSys/usr/bin/bsh instead.

Authorization:
• If AUTHORIZATION_NAME is *CURRENT or matches the caller of this procedure, no authorization is
needed.
• Otherwise, the caller must have:
– *SECADM special authority, and
– *OBJMGT and *USE authorities to the user profile identified by AUTHORIZATION_NAME.

Database performance and query optimization 515


SET_PASE_SHELL_INFO ( authorization-name
AUTHORIZATION_NAME =>

, shell-path )
SHELL_PATH =>

The schema is QSYS2.

authorization- A character or graphic string expression that identifies an existing user profile name.
name Can also be one of the following special values:

*CURRENT Set the current user's shell.


*DEFAULT Set the PASE shell to be used by any user that does not have an explicit
value set. The default does not apply to IBM supplied profiles.
The default is saved in the QSYS user profile. This is equivalent to
specifying 'QSYS' for authorization-name.

shell-path A character or graphic string expression that specifies the path to a PASE shell. The
string must begin with a forward slash (/).
If shell-path is blanks, the empty string, or NULL, the shell path is removed for the
user. Once the path is removed, the value specified for *DEFAULT (if any) will apply to
this user.

Examples
• Set the current user's shell to BASH shipped by 5733-OPS.

CALL QSYS2.SET_PASE_SHELL_INFO('*CURRENT',
'/QOpenSys/QIBM/ProdData/OPS/tools/bin/bash');

• Set the default shell to be ksh for any users that do not have an explicit shell set.

CALL QSYS2.SET_PASE_SHELL_INFO('*DEFAULT', '/QOpenSys/usr/bin/ksh');

SPLIT table function


The SPLIT table function returns a result table that contains one row for each substring of input-list that is
separated by delimiter.
Authorization: None required.

SPLIT ( input-list ,
INPUT_LIST => DELIMITER =>

delimiter )
, escape
ESCAPE =>

input-list An expression that contains a list to be deconstructed. The value is cast to CLOB(2G).
delimiter A character string expression that defines the separator between list elements. The value is
cast to VARCHAR(32672).
escape A character string expression with a length of 1 that defines a character that is used to escape
a delimiter sequence. If this parameter is provided, any delimiter sequence of characters
immediately proceeded by this character will not be interpreted as a delimiter. The escape
character will be removed from the returned element value.

516 IBM i: Performance and Query Optimization


The table function returns one row for each substring of input-list containing the characters between
delimiter strings. If input-list contains two adjacent delimiter strings, an empty string is returned to
represent an element with no content. If a delimiter string starts at position 1 of input-list, a row
containing a zero length string is returned as the first element. If a delimiter string ends at the last position
of input-list, a row containing a zero length string is returned as the last element. Substrings of input-list
that match delimiter are not included in the result.
If input-list is null, the result contains no rows. If delimiter is null, the empty string, or a string that is not
found, input-list is returned.
The result of the function is a table containing a row for each substring of input-list. The columns of the
result table are described in the following table. The result columns are nullable.
Table 105. SPLIT table function

Column Name Data Type Description

ORDINAL INTEGER The relative position of this element in the input string. The first row has a
value of 1.

ELEMENT CLOB(2G) The value of the element.

Note
This function is provided in the SYSTOOLS schema as an example of how to break a string apart at
a delimiting character by using an SQL table function. Similar to other Db2 for i provided tools within
SYSTOOLS, the SQL source can be extracted and used as a model for building similar helper functions, or
to create a customized version within a user-specified schema.

Example
• Return a list of all authorities collected for all users for objects in the APP1 schema. First, a common
table expression breaks the detailed authority lists into separate rows for each authority using the
SPLIT table function. Then, all the authorities for the object are recombined into a single list for
each user, removing duplicate authorities and listing them alphabetically, using the LISTAGG aggregate
function.

WITH EXPANDED_AUTHS AS (
SELECT AUTHORIZATION_NAME, OBJECT_NAME, VARCHAR(TRIM(ELEMENT), 10) AS AUTH
FROM QSYS2.AUTHORITY_COLLECTION,
TABLE(SYSTOOLS.SPLIT(DETAILED_REQUIRED_AUTHORITY, ' '))
WHERE OBJECT_SCHEMA = 'APP1'
AND CHECK_ANY_AUTHORITY = 0)
SELECT AUTHORIZATION_NAME, OBJECT_NAME,
LISTAGG(DISTINCT AUTH, ' ') WITHIN GROUP(ORDER BY AUTH)
FROM EXPANDED_AUTHS
GROUP BY AUTHORIZATION_NAME, OBJECT_NAME
ORDER BY AUTHORIZATION_NAME, OBJECT_NAME;

STACK_INFO table function


The STACK_INFO table function returns one row for each entry in the call stack for either a specific thread
or for every thread of the specified job. It returns information similar to what can be accessed through the
Display Job (DSPJOB) CL command and the Retrieve Call Stack (QWVRCSTK) API.
Authorization: None required to see information for jobs where the caller's user profile is the same as
the job user identity of the job for which the information is being returned. Otherwise, the caller must
have *JOBCTL special authority or be authorized to the QIBM_SERVICE_THREAD function usage identifier.
If the caller has *SERVICE special authority, the returned call stack information will include Licensed
Internal Code (LIC) stack entries.

Database performance and query optimization 517


STACK_INFO (
job-name
JOB_NAME =>

, thread-id
THREAD_ID =>

)
, ignore-errors
IGNORE_ERRORS =>

The schema is QSYS2.

job-name The qualified job name to return stack information. Can contain the following special value:

* The current job name is used.

If job-name is not specified, the default is *.


thread-id A numeric expression indicating the thread identifier to return information for. Can contain
one of the following special values:

ALL Information for all the threads in the job is returned.


INITIAL Information for the initial thread of the job is returned.

If thread-id is not specified:


• If job-name is *, the default is the value of the QSYS2.THREAD_ID global variable.
• Otherwise, the default is INITIAL.

ignore- A character or graphic string expression that identifies what to do when an error is
errors encountered.

NO An error is returned.
YES A warning is returned.
No rows are returned when an error is encountered. This is the default.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 106. STACK_INFO table function

Column Name Data Type Description

THREAD_ID BIGINT The identifier for the specific thread.

THREAD_TYPE VARCHAR(6) Specifies how the thread was initiated.

SYSTEM The thread was initiated by the operating system.

USER The thread was initiated by a user process.

Contains the null value unless ALL was specified for the thread-id
input parameter.

ORDINAL_POSITION INTEGER A unique number for each row corresponding to a thread where 1 is
the first invocation entry for this thread and the highest number is the
most recent invocation entry for this thread.

518 IBM i: Performance and Query Optimization


Table 106. STACK_INFO table function (continued)

Column Name Data Type Description

ENTRY_TYPE VARCHAR(4) The type of stack entry.

ILE This entry returns ILE program information. The columns


specific to JAVA, PASE, and LIC contain the null value.

JAVA This entry returns JAVA information. The columns specific to


ILE and OPM, PASE, and LIC contain the null value.

LIC This entry returns Licensed Internal Code (LIC) information.


The columns specific to ILE and OPM, JAVA, and PASE
contain the null value.

OPM This entry returns OPM program information. The columns


specific to JAVA, PASE, and LIC contain the null value.

PASE This entry returns PASE information. The columns specific to


ILE and OPM, JAVA, and LIC contain the null value.

––– ILE and OPM information ––––––––

PROGRAM_NAME VARCHAR(10) The name of the program or service program.


Nullable Contains the null value if the program name is not available.

PROGRAM_LIBRARY_NAME VARCHAR(10) The name of the library in which the program is located.
Nullable Contains the null value if the program is not located in a library or if
the program library name is not available.

STATEMENT_IDENTIFIERS VARCHAR(109) The high-level language statement identifier. If this column contains
Nullable the character representation of a number, the number is right-
adjusted and padded on the left with zeros (for example,
'0000000246'). If the call stack entry is for an integrated language
environment (ILE) procedure, more than one statement identifier may
exist. If more than one statement identifier is returned, each identifier
will be ten characters long with a single blank between them. Up to
ten identifiers will be returned.
Returns the null value if a statement identifier cannot be determined.

REQUEST_LEVEL INTEGER The level of the request-processing program or procedure.


Nullable Contains the null value if the program or procedure has not received a
request message or incomplete information is available.

CONTROL_BOUNDARY VARCHAR(3) Whether a control boundary exists for a program or procedure. A


Nullable control boundary is defined as any ILE call stack entry for which the
immediately preceding call stack entry is for an ILE procedure or
program object in a different activation group.

NO No control boundary is active.

YES A control boundary is active.

Contains the null value if information is not available or incomplete


information is available.

PROGRAM_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) device in which the
Nullable program is located. Can contain the following special value:

*SYSBAS The program is located in the system ASP or a basic user


ASP

Contains the null value if the name of the ASP cannot be determined.

PROGRAM_ASP_NUMBER INTEGER The numeric identifier of the ASP containing the program.
Nullable
1 The program is in the system ASP.

2-32 The program is in a basic user ASP.

33-255 The program is in an independent ASP.

Contains the null value if the ASP device cannot be determined.

MODULE_NAME VARCHAR(10) The module containing the integrated language environment (ILE)
Nullable procedure.
Contains the null value if this is not an ILE program or if the module
name is not available.

Database performance and query optimization 519


Table 106. STACK_INFO table function (continued)

Column Name Data Type Description

MODULE_LIBRARY_NAME VARCHAR(10) The name of the library in which the module is located.
Nullable Contains the null value if this is not an ILE program or if the module
library name is not available.

PROCEDURE_NAME VARCHAR(4096) The name of the procedure at this level of the call stack.
Nullable Returns the null value if this is not an ILE program or if the procedure
name cannot be determined.

ACTIVATION_GROUP_NUMBER DECIMAL(20,0) The number of the activation group within which the program or
Nullable procedure is running. This is an internal number that uniquely
identifies the activation group within the job.
Contains the null value if this is not an ILE program or incomplete
information is available.

ACTIVATION_GROUP_NAME VARCHAR(10) The name of the activation group within which the program or
Nullable procedure is running. Can contain the following special values:

*DFTACTGRP The activation group does not have a specific name.


The activation group is one of the default activation
groups for the system.

*NEW The activation group does not have a specific name.


The activation group was created when the program
was called.

Contains the null value if this is not an ILE program or incomplete


information is available.

MI_INSTRUCTION_NUMBER INTEGER The current machine instruction number in the program.


Nullable Contains the null value if this is not an OPM program.

––– JAVA information ––––––––

JAVA_LINE_NUMBER INTEGER The line number where the invocation was interrupted.
Nullable Contains the null value if no line number can be determined.

JAVA_BYTE_CODE_OFFSET INTEGER The offset in bytes from the beginning of the Java method byte codes
Nullable to the resume point for the invocation.
Contains the null value if no Java byte code offset can be determined.

JAVA_METHOD_TYPE VARCHAR(9) The type of Java method.


Nullable
DE The method is a direct execution Java method. The
Java method has been precompiled by the Java
Transformer.

GLUE The invocation is a Java Virtual Machine glue frame


used either to perform a call from the JVM to a Java
method or perform a call to a Java native method.

INTERPRET The method is an interpreted Java method. The Java


method is being interpreted by the Java Interpreter.

JIT The method is a JIT compiled Java method. The Java


method has been compiled by the Java Just In Time
Compiler.

MMI The method is a MMI interpreted Java method. The


Java method is being interpreted by the Mixed Mode
Java Interpreter.

Contains the null value if there is no information.

JAVA_CLASS_NAME DBCLOB(64000) CCSID 1200 The name of the Java class at this level of the call stack.
Nullable Returns the null value if the class name cannot be determined.

JAVA_METHOD_NAME DBCLOB(64000) CCSID 1200 The name of the Java method at this level of the call stack.
Nullable Returns the null value if the method name cannot be determined.

JAVA_METHOD_SIGNATURE DBCLOB(64000) CCSID 1200 The signature of the Java method at this level of the call stack.
Nullable Returns the null value if the signature cannot be determined.

520 IBM i: Performance and Query Optimization


Table 106. STACK_INFO table function (continued)

Column Name Data Type Description

JAVA_FILE_NAME DBCLOB(64000) CCSID 1200 The name of the Java file and directory that provides the location of
Nullable where the Java class was loaded at this level of the call stack. If the
Java class was loaded from a .jar or .zip file, then the location will be
the path to and the name of the .jar or .zip file. If the class was loaded
from a .class file, then the location will be the directory from which
the class was loaded.
Returns the null value if the file name cannot be determined.

JAVA_SOURCE_FILE_NAME DBCLOB(64000) CCSID 1200 The name of the Java source file at this level of the call stack.
Nullable Returns the null value if the source file name cannot be determined.

––– PASE information –––––––

PASE_LINE_NUMBER BIGINT The line number where the invocation was interrupted.
Nullable Contains the null value if no line number can be determined.

PASE_INSTRUCTION_ADDRESS DECIMAL(20,0) The IBM PASE for i memory address for the instruction that will run
Nullable when execution resumes for the invocation.

PASE_INSTRUCTION_OFFSET BIGINT The offset in bytes from the beginning of the start of the procedure to
Nullable the instruction that is either the suspend point for the invocation or
the resume point for the invocation.

PASE_KERNEL_CODE VARCHAR(3) Whether the invocation is running IBM PASE for i kernel code.
Nullable
NO The current invocation is not IBM PASE for i kernel code.

YES The current invocation is IBM PASE for i kernel code.

Contains the null value if there is no information.

PASE_BIT_CODE INTEGER Whether the invocation is running 32-bit or 64-bit IBM PASE for i
Nullable code.

32 The invocation is running 32-bit IBM PASE for i code.

64 The invocation is running 64-bit IBM PASE for i code.

Contains the null value if PASE_KERNEL_CODE is YES.

PASE_ALTERNATE_RESUME_POINT VARCHAR(3) Whether the current entry is a second entry for a given invocation.
Nullable This flag is only used when the system can not reliably determine
which of two possible resume points will be used when an invocation
resumes execution.

NO The current invocation does not have an alternate resume


point.

YES The current invocation has an alternate resume point.

Contains the null value if there is no information.

PASE_PROCEDURE_NAME DBCLOB(4000) CCSID 1200 The name of the procedure at this level of the call stack.
Nullable Returns the null value if the procedure name cannot be determined.

PASE_LOAD_MODULE_NAME DBCLOB(1000) CCSID 1200 The name of the load module at this level of the call stack.
Nullable Returns the null value if the load module name cannot be determined.

PASE_LOAD_MODULE_PATH DBCLOB(4000) CCSID 1200 The path to the load module at this level of the call stack.
Nullable Returns the null value if the load module path cannot be determined.

PASE_SOURCE_PATH_AND_FILE DBCLOB(1000) CCSID 1200 The path and name for the source file used to create the procedure.
Nullable Returns the null value if the path and name for the source file cannot
be determined.

––– LIC information –––––––

LIC_INSTRUCTION_OFFSET BIGINT The offset in bytes from the beginning of the start of the procedure to
Nullable the instruction that is either the suspend point for the invocation or
the resume point for the invocation.

Database performance and query optimization 521


Table 106. STACK_INFO table function (continued)

Column Name Data Type Description

LIC_PROCEDURE_NAME VARCHAR(4096) The name of the procedure at this level of the call stack.
Nullable Returns the null value if the procedure name cannot be determined.

LIC_LOAD_MODULE_NAME VARCHAR(64) The name of the load module at this level of the call stack.
Nullable Returns the null value if the load module name cannot be determined.

Example
• Find out whether ILE program MYPGM is on the stack for the current thread.

SELECT * FROM TABLE(QSYS2.STACK_INFO('*')) A


WHERE PROGRAM_NAME = 'MYPGM';

• Create a table that contains the stack for all of the threads in a specific job.

CREATE TABLE STACK_DUMP AS (


SELECT * FROM TABLE(QSYS2.STACK_INFO('358788/QLIWISVR/ADMIN1', 'ALL')) AS X
) WITH DATA;

USER_INDEX_ENTRIES table function


The USER_INDEX_ENTRIES table function returns the entries of the specified user index (*USRIDX). The
data is returned as character and binary data.
The values returned for the result columns of the table function are closely related to the values returned
by the Retrieve User Index Entries (QUSRTVUI) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the user index, and
• *USE authority to the user index.

USER_INDEX_ENTRIES ( user-index
USER_INDEX =>

)
, user-index-library
USER_INDEX_LIBRARY =>

The schema is QSYS2.

user-index A character or graphic string containing the name of the user index.
user-index- A character or graphic string containing the name of the library containing the user
library index. Can be one of the following special values:

*CURLIB The job's current library is used.


*LIBL The library list is used. This is the default.

The result of the function is a table containing one or more rows with the format shown in the following
table. All the columns are nullable.
Table 107. USER_INDEX_ENTRIES table function

Column Name Data Type Description

ORDINAL_POSITION INTEGER The relative position of this row in the result data set.

USER_INDEX_LIBRARY VARCHAR(10) The library in which the user index was found.

USER_INDEX VARCHAR(10) The name of the user index.

522 IBM i: Performance and Query Optimization


Table 107. USER_INDEX_ENTRIES table function (continued)

Column Name Data Type Description

KEY VARCHAR(2000) The key for the index entry in character form.
Contains the null value if the user index is not keyed.

KEY_BINARY VARBINARY(2000) The key for the index entry in binary form. This is the raw form of the data.
Contains the null value if the user index is not keyed.

ENTRY VARCHAR(2000) The data for the index entry in character form.
Contains the null value if the entry contains only a key value.

ENTRY_BINARY VARBINARY(2000) The data for the index entry in binary form. This is the raw form of the data.
Contains the null value if the entry contains only a key value.

Example
Look at all the entries in user index IX1 in TESTLIB.

SELECT * FROM TABLE(QSYS2.USER_INDEX_ENTRIES(


USER_INDEX => 'IX1',
USER_INDEX_LIBRARY => 'TESTLIB'))
ORDER BY ORDINAL_POSITION;

USER_INDEX_INFO view
The USER_INDEX_INFO view returns the attributes of user indexes.
The values returned for the columns in the view are closely related to the values returned by the Retrieve
User Index Attributes (QUSRUIAT) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the user index, and
• *USE authority to the user index.
The following table describes the columns in the view. The system name is USRIDX_INF. The schema is
QSYS2.
Table 108. USER_INDEX_INFO view

Column Name System Column Name Data Type Description

USER_INDEX_LIBRARY USRIDX_LIB VARCHAR(10) Library containing the user index.

USER_INDEX USRIDX VARCHAR(10) Name of the user index.

ENTRY_TYPE TYPE VARCHAR(8) The type of entries in the user index.

FIXED Fixed-length entries

VARIABLE Variable-length entries

ENTRY_LENGTH LENGTH INTEGER When ENTRY_TYPE is FIXED, the length of each


index entry. When ENTRY_TYPE is VARIABLE, the
length of the longest entry that has ever been
inserted into the index.
Valid values are from 1 through 2000.

MAXIMUM_ENTRY_LENGTH MAX_LENGTH INTEGER The maximum entry length any user index entry
can have.

INDEX_SIZE SIZE CHAR(4) The maximum size of the user index.

4 GB The maximum size of the user index is 4


gigabytes.

1 TB The maximum size of the user index is 1


terabyte.

Database performance and query optimization 523


Table 108. USER_INDEX_INFO view (continued)

Column Name System Column Name Data Type Description

IMMEDIATE_UPDATE IMMEDIATE VARCHAR(3) Whether updates to the index are written to


auxiliary storage on each update to the index.

NO No immediate update

YES Immediate update

OPTIMIZATION OPTIMIZE VARCHAR(10) The optimization method used for user index
maintenance.

RANDOM Random references

SEQUENTIAL Sequential references

KEY_INSERTION KEYED VARCHAR(3) Whether inserts into the index are by key.

NO No insertion by key

YES Insertion by key

KEY_LENGTH KEY_LENGTH INTEGER The length of the key.

Nullable Contains the null value when KEY_INSERTION is


NO.

ENTRY_TOTAL TOTAL INTEGER The number of entries currently in the index.

ENTRIES_ADDED ADDED INTEGER The number of entries added to the user index.

ENTRIES_REMOVED REMOVED INTEGER The number of entries removed from the user
index.

OBJECT_DOMAIN DOMAIN VARCHAR(7) The domain of the object.

*SYSTEM The object is in the system domain.

*USER The object is in the user domain.

TEXT_DESCRIPTION TEXT VARCHAR(50) The text description of the user index.

Nullable Contains the null value if the user index has no


description.

Example
• Return a list of attributes for all user indexes in MYLIB.

SELECT * FROM QSYS2.USER_INDEX_INFO


WHERE USER_INDEX_LIBRARY = 'MYLIB';

USER_SPACE table function


The USER_SPACE table function returns the contents of the specified user space (*USRSPC). The data is
returned as character and binary data.
The values returned for the result columns of the table function are closely related to the values returned
by the Retrieve User Space (QUSRTVUS) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the user space, and
• *USE authority to the user space.

524 IBM i: Performance and Query Optimization


USER_SPACE ( user-space
USER_SPACE =>

)
, user-space-library
USER_SPACE_LIBRARY =>

The schema is QSYS2.

user-space A character or graphic string containing the name of the user space.
user-space- A character or graphic string containing the name of the library containing the user
library space. Can be one of the following special values:

*CURLIB The job's current library is used.


*LIBL The library list is used. This is the default.

The result of the function is a table containing one row with the format shown in the following table. All
the columns are nullable.
Table 109. USER_SPACE table function

Column Name Data Type Description

USER_SPACE_LIBRARY VARCHAR(10) The library in which the user space was found.

USER_SPACE VARCHAR(10) The name of the user space.

DATA CLOB(16M) The data from the user space as character data.

DATA_BINARY BLOB(16M) The data from the user space in binary form. This is the raw form of the data.

Example
Look at the untranslated contents of user space USERSPC1 in TESTLIB.

SELECT DATA_BINARY FROM TABLE(QSYS2.USER_SPACE(


USER_SPACE => 'USRSPACE1',
USER_SPACE_LIBRARY => 'TESTLIB'));

USER_SPACE_INFO view
The USER_SPACE_INFO view returns the attributes of user spaces.
The values returned for the columns in the view are closely related to the values returned by the Retrieve
User Space Attributes (QUSRUSAT) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the user space, and
• *USE authority to the user space.
The following table describes the columns in the view. The system name is USRSPC_INF. The schema is
QSYS2.
Table 110. USER_SPACE_INFO view

Column Name System Column Name Data Type Description

USER_SPACE_LIBRARY USRSPC_LIB VARCHAR(10) Library containing the user space.

USER_SPACE USRSPC VARCHAR(10) Name of the user space.

SIZE SIZE INTEGER The size of the user space object in bytes.

Database performance and query optimization 525


Table 110. USER_SPACE_INFO view (continued)

Column Name System Column Name Data Type Description

EXTENDABLE EXTENDABLE VARCHAR(3) Whether the space is extended automatically


by the system when the end of the space is
encountered.

NO Space is not automatically extendable

YES Space is automatically extendable

INITIAL_VALUE INITIAL BINARY(1) The initial value to which future extensions of the
user space will be set.

OBJECT_DOMAIN DOMAIN VARCHAR(7) The domain of the object.

*SYSTEM The object is in the system domain.

*USER The object is in the user domain.

TEXT_DESCRIPTION TEXT VARCHAR(50) The text description of the user space.

Nullable Contains the null value if the user space has no


description.

Example
• Return a list of user spaces in MYLIB.

SELECT USER_SPACE, SIZE, TEXT_DESCRIPTION FROM QSYS2.USER_SPACE_INFO


WHERE USER_SPACE_LIBRARY = 'MYLIB';

WATCH_DETAIL table function


The WATCH_DETAIL table function returns the details for watched messages, LIC logs, and PALs for a
specific session identifier.
The values returned for the columns in the table function are closely related to the values returned by the
WRKWCH (Work with Watches) CL command and by the Retrieve Watch Information (QSCRWCHI) API.
Authorization: The caller must have:
• *USE authority to the QSYS/QSCRWCHI program, and
– *SERVICE special authority, or
– Authorization to the QIBM_SERVICE_WATCH and QIBM_SERVICE_TRACE function usage identifiers.

WATCH_DETAIL ( session-id )
SESSION_ID =>

The schema is QSYS2.

session-id A character or graphic string expression that contains the session identifier that the watch
details are returned for.

The result of the function is a table containing rows with the format shown in the following table. All
columns are nullable.
Table 111. WATCH_DETAIL table function

Column Name Data Type Description

DETAIL_TYPE VARCHAR(7) The type of detail information returned by this row.

LICLOG This row is for a watched LIC log.

MESSAGE This row is for a watched message.

PAL This row is for a watched PAL.

526 IBM i: Performance and Query Optimization


Table 111. WATCH_DETAIL table function (continued)

Column Name Data Type Description

COMPARISON_DATA_CCSID INTEGER The CCSID that pertains to each of the xxx_COMPARISON_DATA


columns.
Contains the null value if this row has no comparison data.

The following columns apply when DETAIL_TYPE is MESSAGE. They will contain the null value when DETAIL_TYPE is LICLOG or PAL.

MESSAGE_ID VARCHAR(7) The message to be watched.

message-id The 7-character message identifier of the message to


be watched.

generic-name The generic name of the message to be watched.


A generic name is a character string of one or
more characters followed by an asterisk (*); for
example, ABC*. The asterisk substitutes for any valid
characters. A generic message name specifies all
messages with identifiers that begin with the generic
prefix.

*ALL All messages are to be watched. This includes stored


messages and immediate messages.

*IMMED All immediate or impromptu messages will be


watched.

MESSAGE_TYPE VARCHAR(6) The message type assigned to the message to be watched.

ALL All the message types are to be watched. This includes


completion, command, diagnostic, escape, informational,
inquiry, notify, reply, request, sender's copy, scope and
status message types.

COMP A completion message is to be watched.

DIAG A diagnostic message is to be watched.

ESCAPE An escape message is to be watched.

INFO An informational message is to be watched.

INQ An inquiry message is to be watched.

NOTIFY A notify message is to be watched.

SCOPE A scope message is to be watched.

STATUS A status message is to be watched.

MESSAGE_QUEUE_LIBRARY VARCHAR(10) The name of the library where the message queue is located.
Contains the null value if MESSAGE_QUEUE is *JOBLOG.

MESSAGE_QUEUE VARCHAR(10) The name of the message queue to watch. Can contain the following
special value:

*JOBLOG Watch messages added to the job logs of the jobs


specified for the watched job field.

MESSAGE_JOB_NAME VARCHAR(10) The job name of the job to be watched. Can contain the following
special values:

generic- The generic name of the job to be watched. A generic


name name is a character string of one or more characters
followed by an asterisk (*); for example, ABC*. The
asterisk substitutes for any valid characters. A generic
job name specifies all jobs with job names that begin
with the generic prefix.

*ALL All jobs with the specified job user name are watched.

Contains the null value if MESSAGE_QUEUE is not *JOBLOG.

Database performance and query optimization 527


Table 111. WATCH_DETAIL table function (continued)

Column Name Data Type Description

MESSAGE_JOB_USER VARCHAR(10) The user name of the job to be watched. Can contain the following
special values:

generic- The generic name of the user name of the job to be


name watched. A generic name is a character string of one or
more characters followed by an asterisk (*); for example,
ABC*. The asterisk substitutes for any valid characters. A
generic user name specifies all jobs with the specified
job name and with user names that begin with the
generic prefix.

*ALL All jobs with the specified job name are watched.

Contains the null value if MESSAGE_QUEUE is not *JOBLOG.

MESSAGE_JOB_NUMBER VARCHAR(6) The job number to further qualify the job name and user name. Can
contain the following special value:

*ALL All jobs with the specified job name and user name are
watched.

Contains the null value if a generic job name or a generic user name
qualifier is specified, or if MESSAGE_QUEUE is not *JOBLOG.

MESSAGE_SEVERITY INTEGER The severity code, ranging from 0 through 99, of the message to be
watched.

MESSAGE_RELATIONAL_OPERATOR CHAR(3) The relational operator against which the message severity code is
compared.

*EQ Equal

*GE Greater than or equal

*GT Greater than

*LE Less than or equal

*LT Less than

MESSAGE_COMPARISON_DATA VARCHAR(72) CCSID 65535 The comparison data to be used if a message matching the specified
message is added to the specified message queue or log. If the
message data, the "From program" or the "To program" includes the
specified text, the watched for condition is true.
Contains the null value if no message comparison data was specified.

MESSAGE_COMPARE_AGAINST VARCHAR(8) The part of the message the data specified in


MESSAGE_COMPARISON_DATA is to be compared against.

*FROMPGM The message comparison data will be compared


against the name of the program sending the message,
or the name of the ILE program that contains the
procedure sending the message.

*MSGDTA The message comparison data will be compared


against the message replacement data.

*TOPGM The message comparison data will be compared


against the name of the program the message was sent
to, or the name of the ILE program that contains the
procedure the message was sent to.

Contains the null value if no message comparison data was specified.

The following columns apply when DETAIL_TYPE is LICLOG. They will contain the null value when DETAIL_TYPE is MESSAGE or PAL.

LIC_MAJOR_CODE CHAR(4) The LIC log major code to be watched. A hexadecimal digit or a
question mark can be specified for each character in the four-digit code.
A question mark is a wildcard character that will match any digit in that
position. Up to three wildcard characters can be specified. Can contain
the following special value:

*ALL Any LIC log entry major code will be considered to be a match.

528 IBM i: Performance and Query Optimization


Table 111. WATCH_DETAIL table function (continued)

Column Name Data Type Description

LIC_MINOR_CODE CHAR(4) The LIC log minor code to be watched. A hexadecimal digit or a
question mark can be specified for each character in the four-digit code.
A question mark is a wildcard character that will match any digit in that
position. Up to three wildcard characters can be specified. Can contain
the following special value:

*ALL Any LIC log entry minor code will be considered to be a match.

LIC_COMPARISON_DATA VARCHAR(72) CCSID 65535 The comparison data to be used if a log entry matching the specified
major and minor codes is added to the licensed internal code (LIC)
log. If this text is found in the LIC log entry data field specified by
the LIC log compare against field, the watched for condition is true.
This text is case sensitive. If *ALL is specified in the LIC log compare
against field, the LIC log fields which will be compared are TDE number,
task name, server type, job name, user ID, job number, thread ID,
exception ID, LIC module compile binary timestamp, module offset, LIC
module RU name, LIC module name, LIC module entry point name. The
comparison data cannot be used to match across two fields, and can
match an entire field or a substring of any field. The prefix MCH may
be specified to compare only against the exception ID field and avoid
possible substring matches with the other fields.
Contains the null value if no LIC log comparison data was specified.

Database performance and query optimization 529


Table 111. WATCH_DETAIL table function (continued)

Column Name Data Type Description

LIC_COMPARE_AGAINST VARCHAR(10) The part of the LIC log the data specified in LIC_COMPARISON_DATA is
to be compared against.

*ALL The LIC log comparison data will be compared


against all the fields described below.

*EXCPID The LIC log comparison data will be compared


against the exception that caused the LIC log entry
to be requested. This is a 2-byte hexadecimal
field formed by concatenating to the high-order 1-
byte exception group number a low-order 1-byte
exception subtype number. Exception identifier is
binary zeros if the LIC log entry is not requested as a
result of an exception.

*JOBNAME The LIC log comparison data will be compared


against the name of the job which requested the LIC
log entry. LIC job name is blank (hex 40s) if the LIC
log entry is not requested by a job.

*JOBNBR The LIC log comparison data will be compared


against the job number (000001-999999) to further
qualify the job name and user name of the job which
requested the LIC log entry. LIC job number is blank
(hex 40s) if the LIC log entry is not requested by a
job.

*JOBUSR The LIC log comparison data will be compared


against the user name of the job which requested
the LIC log entry. LIC user name is blank (hex 40s) if
the LIC log entry is not requested by a job.

*MODEPNAME The LIC log comparison data will be compared


against the name of the entry point which requested
the LIC log entry. If the entry point name is greater
than 128 characters, the LIC module entry point
name is truncated to 128 characters.

*MODNAME The LIC log comparison data will be compared


against the LIC module name which requested the
LIC log entry. If the module name is greater than 64
characters, the LIC module name is truncated to 64
characters.

*MODOFFSET The LIC log comparison data will be compared


against the byte offset into the LIC module text
which requested the LIC log entry.

*MODRUNAME The LIC log comparison data will be compared


against the LIC module replacement unit name. LIC
module RU name is always in upper case EBCDIC.

*MODTSP The LIC log comparison data will be compared


against the timestamp of when the LIC module was
compiled. The format for this field is the system
timestamp format.

*SVRTYPE The LIC log comparison data will be compared


against the type of server that requested the LIC
log entry. Server type is blank (hex 40s) if the LIC
log entry is not requested by a server.

*TASKNAME The LIC log comparison data will be compared


against the name of the task which requested the
LIC log entry. Task name is blank (hex 40s) if the LIC
log entry is not requested by a task.

*TDENBR The LIC log comparison data will be compared


against the number of the task dispatching element
(TDE) which requested the LIC log entry.

*THDID The LIC log comparison data will be compared


against the thread which requested the LIC log
entry. Thread identifier is binary zeros if the LIC log
entry is not requested by a thread

Contains the null value if no LIC log comparison data was specified.

The following columns apply when DETAIL_TYPE is PAL. They will contain the null value when DETAIL_TYPE is MESSAGE or LICLOG.

530 IBM i: Performance and Query Optimization


Table 111. WATCH_DETAIL table function (continued)

Column Name Data Type Description

PAL_SYSTEM_REFERENCE_CODE VARCHAR(8) The system reference code to be watched. A hexadecimal digit or a


question mark can be specified for each character in the eight-digit
code. A question mark is a wildcard character that will match any digit
in that position. Up to seven wildcard characters can be specified.
A generic name that is a character string of one or more characters
followed by an asterisk (*) can also be specified; for example, ABC*. The
asterisk substitutes for any valid characters. A generic name specifies
all PALs with system reference codes that begin with the generic prefix.
Can contain the following special value:

*ALL Any PAL system reference code will be considered to be a


match.

PAL_COMPARISON_DATA VARCHAR(10) CCSID 65535 The comparison data to be used if a PAL entry matching the specified
system reference code was created. If the data specified by PAL
compare against field matches the specified text, the watched for
condition is true. This text is case sensitive. Question marks (?) and
asterisk (*) wildcard characters can be specified in the text string. A
question mark is a single-character wildcard character and will match
any character in the same position. For example, '??123' will match
any value that is five characters long and ends with '123'. Multiple
question mark wildcard characters can be specified for the comparison
data value. An asterisk is a multiple-character wildcard character. A
single asterisk wildcard character can be specified at the end of the
comparison data value. For example, 'ABC*' will match any value that
begins with the letters 'ABC'.
Contains the null value if no PAL comparison data was specified.

PAL_COMPARE_AGAINST VARCHAR(9) The part of the PAL the data specified in PAL_COMPARISON_DATA is to
be compared against.

*RSCMODEL The PAL comparison data will be compared against the


resource model.

*RSCNAME The PAL comparison data will be compared against the


resource name.

*RSCTYPE The PAL comparison data will be compared against the


resource type.

Contains the null value if no PAL comparison data was specified.

Example
• List all the watches that my user profile started with the STRWCH command including the detailed
information.

SELECT *
FROM QSYS2.WATCH_INFO W, TABLE(QSYS2.WATCH_DETAIL(W.SESSION_ID)) D
WHERE W.WATCH_SESSION_TYPE = '*STRWCH' AND
W.USER_ID = USER;

WATCH_INFO view
The WATCH_INFO view returns information about watch sessions on the system.
The values returned for the columns in the view are closely related to the values returned by the
WRKWCH (Work with Watches) CL command and by the Retrieve Watch List (QSCRWCHL) and Retrieve
Watch Information (QSCRWCHI) API.
Authorization: The caller must have:
• *USE authority to the QSYS/QSCRWCHL and QSYS/QSCRWCHI programs, and
• – *SERVICE special authority, or
– Authorization to the QIBM_SERVICE_WATCH and QIBM_SERVICE_TRACE function usage identifiers.
The following table describes the columns in the view. The system name is WATCH_INFO. The schema is
QSYS2.

Database performance and query optimization 531


Table 112. WATCH_INFO view

Column Name System Column Name Data Type Description

SESSION_ID SESSION_ID VARCHAR(10) The session identifier for the watch.

ORIGIN ORIGIN VARCHAR(9) The name of the command or the API that started
the watch.

QSCSWCH Session started by Start Watch


(QSCSWCH) API.

STRCMNTRC Session started by


Start Communications Trace
(STRCMNTRC) command.

STRTRC Session started by Start Trace


(STRTRC) command.

STRWCH Session started by Start Watch


(STRWCH) command.

TRCCNN Session started by


Trace Connection (TRCCNN)
command.

TRCINT Session started by Trace Internal


(TRCINT) command.

TRCTCPAPP Session started by Trace


TCP/IP Application (TRCTCPAPP)
command.

ORIGIN_JOB ORIGIN_JOB VARCHAR(28) The qualified job name that started the watch
session.

START_TIMESTAMP WCH_START TIMESTAMP The timestamp of when the watch was started.

USER_ID USER_ID VARCHAR(10) The name of the user that started the watch
session.

WATCH_SESSION_TYPE WCH_TYPE VARCHAR(7) Identifies the type of watch according to its origin.

*SRVMON Watch session started using the


Service Monitor function of the
operating system.

*STRWCH Watch session started using the


Start Watch (STRWCH) command
or Start Watch (QSCSWCH) API.

*TRCCMD Watch session started using


Start Communications Trace
(STRCMNTRC), Start Trace
(STRTRC), Trace Internal (TRCINT),
Trace Connection (TRCCNN),
or Trace TCP/IP Application
(TRTCPAPP) commands.

STATUS STATUS VARCHAR(6) The status of the watch session.

ACTIVE Session is in ACTIVE status

ENDING Session is in ENDING status

JOB_RUN_PRIORITY PRIORITY INTEGER The priority for the job where the watch session
work will be run.

WATCHED_MESSAGE_COUNT MSG_COUNT INTEGER The number of messages being watched.

WATCHED_LIC_LOG_COUNT LIC_COUNT INTEGER The number of LIC logs being watched.

WATCHED_PAL_COUNT PAL_COUNT INTEGER The number of PALs being watched.

WATCH_PROGRAM_LIBRARY WCH_PGMLIB VARCHAR(10) The name of the library where the watch program
is located.
Nullable
Contains the null value if WATCH_PROGRAM is
null.

WATCH_PROGRAM WCH_PGM VARCHAR(10) The name of the program called to notify that a
specified watch event occurred.
Nullable
Contains the null value if a watch program is not
specified or not found.

532 IBM i: Performance and Query Optimization


Table 112. WATCH_INFO view (continued)

Column Name System Column Name Data Type Description

WATCH_PROGRAM_CALL_START CALL_START VARCHAR(3) Whether the watch program will be called before
starting watching for any event.
Nullable
NO The watch program will not be called
before starting watching for any event.

YES The watch program will be called before


starting watching for any event.

Contains the null value if WATCH_PROGRAM is


null.

WATCH_PROGRAM_CALL_END CALL_END VARCHAR(3) Whether the watch program will be called when
the watch session is ending.
Nullable
NO The watch program will not be called
when the watch session is ending.

YES The watch program will be called when


the watch session is ending.

Contains the null value if WATCH_PROGRAM is


null.

TIME_LIMIT TIME_LIMIT INTEGER The time limit, in minutes, for watching for a
message, a LIC log entry, or a PAL entry. A non-
Nullable null value is only returned for watch sessions
started by a trace command.
When the specified amount of time has elapsed,
the program identified by the WATCH_PROGRAM
column is called, the watch is ended, and
message CPI3999 is sent to the history log.
Contains the null value if the watch session was
started by a trace command and did not specify
a time limit or for sessions not started by a trace
command.

TIME_INTERVAL INTERVAL INTEGER The interval of time, in seconds, of how often the
trace exit program is called.
Nullable
Contains the null value if the watch session was
started by a trace command and did not specify
an interval or for sessions not started by a trace
command.

Example
• List all the service monitor watches that are currently active.

SELECT *
FROM QSYS2.WATCH_INFO
WHERE WATCH_SESSION_TYPE = '*SRVMON' AND
STATUS = 'ACTIVE';

Backup and Recovery Services


These table functions and views provide information about backup and recovery.

Backup, Recovery, and Media Services (BRMS) Services


These table functions and views provide information about BRMS.
BRMS SQL Services

MEDIA_LIBRARY_INFO view
The MEDIA_LIBRARY_INFO view returns information that can also be seen through the Work with Media
Library Status (WRKMLBSTS) command interface.
Authorization: None required.

Database performance and query optimization 533


The following table describes the columns in the view. The system name is MEDIA_INFO. The schema is
QSYS2.
Table 113. MEDIA_LIBRARY_INFO view

Column Name System Column Name Data Type Description

DEVICE_NAME DEVICE VARCHAR(10) The name of the device.

DEVICE_STATUS DEVICE_STS VARCHAR(20) The status of the device. The most common values are:

VARIED ON The media library device is varied on.

VARIED OFF The media library device is varied off.

ACTIVE The resource is currently in use by a job under


this media library.

See List Configuration Descriptions API for a complete list of


status values.

DEVICE_TYPE DEVICE_TYP VARCHAR(10) The type of device. Contains the special value *RSRCNAME
if the device type is determined by the resource in the
RESOURCE_NAME column.

DEVICE_MODEL DEVICE_MDL VARCHAR(10) The model number of the device. Contains the special value
*RSRCNAME if the device model is determined by the resource
in the RESOURCE_NAME column.

RESOURCE_NAME RESOURCE VARCHAR(10) The name of the resource.

Nullable Contains the null value if the DEVICE_STATUS column has a


value of VARIED_OFF, or if the tape library does not have any
associated tape resources.

RESOURCE_STATUS RSRC_STS VARCHAR(11) The status of the resource.

Nullable OPERATIONAL The resource is working and the system can


address the tape drive resource.

ACTIVE The resource is currently in use by a job


under this media library.

UNAVAILABLE The resource is currently not available


because it may be in use by another object,
another client, or DST.

FAILED The resource is not operational and the


system can no longer communicate with that
resource. A hardware problem may have
occurred.

Contains the null value if the DEVICE_STATUS column has a


value of VARIED_OFF, or if the tape library does not have any
associated tape resources.

534 IBM i: Performance and Query Optimization


Table 113. MEDIA_LIBRARY_INFO view (continued)

Column Name System Column Name Data Type Description

RESOURCE_ALLOCATION_STATUS ALLOCATION VARCHAR(11) Current allocation status for the resource.

Nullable ALLOCATED For a tape media library device the resource


is exclusively assigned to this system and
cannot be accessed by another system. For
an optical media library device the drive is
available for use by this media library.

UNPROTECTED A tape resource is not exclusively assigned


to this system. This resource can be
assigned to this system when no other
system has already assigned the resource.

DEALLOCATED For a tape media library the resource is not


assigned to this system and is not available
to respond to requests. For an optical media
library the device is not available for use by
this media library.

STAND-ALONE A tape resource is not available. The tape


resource is reserved by a varied on stand-
alone tape device description for non-library
mode use.

*UNKNOWN An optical media library is varied off or


failed. The current allocation for a resource
cannot be determined.

Contains the null value if the DEVICE_STATUS column has a


value of VARIED_OFF, or if the tape library does not have any
associated tape resources.

RESOURCE_ALLOCATION ALLOC_PRTY VARCHAR(4) The priority of a job when requesting a resource. 1 is highest
_PRIORITY priority, 99 is lowest. Can contain the following special value:

*JOB The priority of the job is used as the resource allocation


priority.

INITIAL_MOUNT_WAIT_TIME INIT_WAIT VARCHAR(6) The maximum amount of time a request will wait for allocation
of a tape resource for the initial mount. Contains either a
numeric string representing the number of minutes or one of
the following special values:

*JOB The allocation wait time is determined by the


default wait time attribute of the job requesting the
allocation, rounded up to the nearest minute.

*IMMED The request will not wait for a tape resource to


become available.

*NOMAX The request will wait until a tape resource is


available.

END_OF_VOLUME_MOUNT_WAIT END_WAIT VARCHAR(6) The maximum amount of time a request will wait for allocation
_TIME of a tape resource for the end of volume mount. Contains either
a numeric string representing the number of minutes or one of
the following special values:

*JOB The allocation wait time is determined by the


default wait time attribute of the job requesting the
allocation, rounded up to the nearest minute.

*IMMED The request will not wait for a tape resource to


become available.

*NOMAX The request will wait until a tape resource is


available.

DEVICE_DESCRIPTION DEVICE_DES VARCHAR(50) The text description of the device.

Example
Return information about all media library devices.

SELECT * FROM QSYS2.MEDIA_LIBRARY_INFO

Database performance and query optimization 535


SAVE_FILE_INFO view
The SAVE_FILE_INFO view returns general information about save files. Detailed information for save
files that contain Integrated File System data is not returned.
The information returned is similar to the detail available through the Display Save File (DSPSAVF) CL
command and the List Save File (QSRLSAVF) API.
Authorization: The caller must have:
• *USE authority to the library containing the save file, and
• *USE authority to the save file.
The following table describes the columns in the view. The system name is SAVF_INFO. The schema is
QSYS2.
Table 114. SAVE_FILE_INFO view

Column Name System Column Name Data Type Description

SAVE_FILE_LIBRARY SAVF_LIB VARCHAR(10) Name of the library that contains the save file.

SAVE_FILE SAVF VARCHAR(10) Name of the save file.

OBJECTS_SAVED OBJECTS INTEGER The number of objects saved for the library.

MEMBERS_SAVED MEMBERS INTEGER The number of members saved for the library.

ACCESS_PATHS_SAVED ACC_PATHS INTEGER The number of logical file access paths saved for the
library.

SPOOLED_FILES_SAVED SPLFS INTEGER The number of spooled files saved in the save file.

SAVE_COMMAND SAVE_CMD VARCHAR(9) The save command that was used for the save
operation.
Nullable
QSYS Contents of the save file were
created by the operating system by
using a function other than the CL
commands.

SAV Save directories and integrated file


system objects. Information about
the content of this save file is not
returned.

SAVCFG Save configuration information.

SAVCHGOBJ Save objects that changed since


the date and time specified on the
referenced date parameter.

SAVDLO Save documents or folders located


in library QDOC.

SAVLIB Save a library.

SAVLICPGM Save licensed programs.

SAVOBJ Save an object or group of objects


from the same library.

SAVSECDTA Save objects required for the


security function.

Contains the null value if the save file is empty.

SAVE_TIMESTAMP SAVED TIMESTAMP(0) The date and time when the objects were saved.

Nullable Contains the null value if the save file is empty or


SAVE_COMMAND is SAV.

DATA_COMPRESSED COMPRESSED VARCHAR(3) Whether the data was saved in compressed format.

Nullable NO The data is not compressed.

YES The data is compressed.

Contains the null value if the save file is empty or


SAVE_COMMAND is SAV.

536 IBM i: Performance and Query Optimization


Table 114. SAVE_FILE_INFO view (continued)

Column Name System Column Name Data Type Description

SAVE_WHILE_ACTIVE SAVEACTIVE VARCHAR(8) Whether objects in the library were allowed to be


updated while they were being saved.
Nullable
*LIB Objects in the library were allowed to
be saved while they were in use by
another job. All objects in the library
reached a checkpoint together. They
were saved in a consistent state in
relationship to each other.

*NO Objects in the library were not allowed


to be saved while they were in use by
another job.

*SYNCLIB Objects in the library were saved while


in use by another job. All of the
objects and all of the libraries in the
save operation reached a checkpoint
together. The objects and the libraries
were saved in a consistent state in
relationship to each other.

*SYSDFN Objects that were in use were saved


if they were released within the
time specified on the SAVACTWAIT
parameter. Objects in the library
may have reached a checkpoint at
different times. They might not be in a
consistent state in relationship to each
other. Objects in the library were saved
while in use by another job.

*YES Document library objects were allowed


to be saved while they were in use by
another job.

Contains the null value if the save file is empty or


SAVE_COMMAND is SAV.

SYNCHRONIZATION_ID SYNC_ID VARCHAR(10) The name that was used to synchronize checkpoints
for more than one save while active operation.
Nullable
Contains the null value if the save file is empty,
SAVE_COMMAND is SAV, or if no synchronization
name was used for the save.

EARLIEST_POSSIBLE_RELEASE EARLY_REL CHAR(6) The earliest release level of the operating system on
which the objects can be restored in VxRxMx format.
Nullable
Contains the null value if the save file is empty or
SAVE_COMMAND is SAV.

LIBRARY_NAME LIBRARY VARCHAR(10) The name of the library from which the objects were
saved.
Nullable
Contains the null value if the save file is empty or
SAVE_COMMAND is SAV.

PRIVATE_AUTHORITIES PRIV_AUTHS VARCHAR(3) Whether the save operation specified that private
authorities should be saved with the objects.
Nullable
NO Objects were saved without their private
authorities.

YES Objects were saved with their private


authorities.

Contains the null value if the save file is empty or


SAVE_COMMAND is SAV.

SERIAL_NUMBER SERIAL VARCHAR(8) The serial number of the system on which the save
was performed.
Nullable
Contains the null value if the serial number is not
available or the save file is empty or SAVE_COMMAND
is SAV.

SAVE_FILE_RECORDS SAVF_REC BIGINT The number of records used to contain the saved
information in the save file.
Nullable
Contains the null value if SAVE_COMMAND is SAV.

Database performance and query optimization 537


Table 114. SAVE_FILE_INFO view (continued)

Column Name System Column Name Data Type Description

IASP_NUMBER IASPNUMBER INTEGER The auxiliary storage pool (ASP) of the library when it
was saved.
Nullable
Contains the null value if the save file is empty or
SAVE_COMMAND is SAV.

IASP_NAME IASPNAME VARCHAR(10) The name of the independent auxiliary storage pool
(ASP) device of the library when it was saved. Can
Nullable contain the special value *SYSBAS.
Contains the null value if the save file is empty or
SAVE_COMMAND is SAV.

Example
• Find all the save files in library BACKUP used to save objects from APPLIB.

SELECT SAVE_FILE_LIBRARY, SAVE_FILE, SAVE_TIMESTAMP, OBJECTS_SAVED


FROM QSYS2.SAVE_FILE_INFO
WHERE SAVE_FILE_LIBRARY = 'BACKUP' AND
LIBRARY_NAME = 'APPLIB';

SAVE_FILE_OBJECTS table function


The SAVE_FILE_OBJECTS table function returns information about the objects in a save file. Information
about Integrated File System objects is not returned.
The information returned is similar to the detail available through the Display Save File (DSPSAVF) CL
command and the List Save File (QSRLSAVF) API.
Authorization: The caller must have:
• *USE authority to the library containing the save file, and
• *USE authority to the save file.

SAVE_FILE_OBJECTS ( save-file
SAVE_FILE =>

, save-file-library
SAVE_FILE_LIBRARY =>

, object-name-filter
OBJECT_NAME_FILTER =>

, object-type-filter
OBJECT_TYPE_FILTER =>

, detailed-info
DETAILED_INFO =>

)
, ignore-errors
IGNORE_ERRORS =>

The schema is QSYS2.

538 IBM i: Performance and Query Optimization


save-file A character or graphic string expression that identifies the name of the save file
containing the objects.
save-file- A character or graphic string expression that identifies the name of the library that
library contains save-file.
The string can contain the following special values:

*CURLIB The current library is used.


*LIBL The library list is used. This is the default.

object-name- A character or graphic string expression that identifies the object name to be returned.
filter The name can be a generic name.
The string can contain the following special value:

*ALL All objects are returned.

If this parameter is not specified, information for all objects is returned.

object-type- A character or graphic string expression that contains a system object type for the
filter objects to be returned.
The string can contain the following special value:

*ALL All object types are returned.

If this parameter is not specified, information for all object types is returned.

detailed-info A character or graphic string expression that indicates the type of information to be
returned.

NONE Only information about the object is returned. This is the default.
FILE Additional information is returned for *FILE objects. For every file, one row is
returned for each member.
OUTQ Additional information is returned for *OUTQ objects. For every output queue,
one row is returned for each spooled file.
ALL Additional information is returned for *FILE and *OUTQ objects.
For a file, one row is returned for each member in the file.
For an output queue, one row is returned for each spooled file in the output
queue.

ignore-errors A character or graphic string expression that identifies what to do when an error is
encountered.

NO An error is returned.

YES A warning is returned.


No row is returned when an error is encountered. This is the default.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 115. SAVE_FILE_OBJECTS table function

Column Name Data Type Description

SAVE_FILE_LIBRARY VARCHAR(10) Name of the library that contains the save file.

SAVE_FILE VARCHAR(10) Name of the save file.

LIBRARY_NAME VARCHAR(10) The name of the library from which the object was saved.

Database performance and query optimization 539


Table 115. SAVE_FILE_OBJECTS table function (continued)

Column Name Data Type Description

OBJECT_NAME VARCHAR(10) The name of the saved object. Contains the system name for a DLO
object.

OBJECT_TYPE VARCHAR(7) The type of object.

OBJECT_ATTRIBUTE VARCHAR(10) Extended information about the object type.


Contains the null value if there is no object attribute.

TEXT_DESCRIPTION VARCHAR(50) The text description of the object.


Contains the null value if there is no text description.

SAVE_TIMESTAMP TIMESTAMP(0) The date and time at which the object was saved.

OBJECT_SIZE BIGINT The size of the object, in bytes. This value will be a rounded value for an
object larger than 999,999,999 bytes.

DATA_SAVED VARCHAR(3) Whether the data for this object was saved with the object.

NO The data was not saved. The object's storage was freed by a
previous save command before this save operation.

YES The data was saved. The object's storage was not freed by a
previous save command before this save operation.

OBJECT_OWNER VARCHAR(10) The owner of the object.

DLO_NAME VARCHAR(20) The name of the document, folder, or mail object that was saved.
Contains the null value if there is no document library object.

FOLDER_PATH VARCHAR(63) The name of the folder that was saved.


Contains the null value if this is not a *FLR or *DOC object, or if there is
no folder path.

IASP_NUMBER INTEGER The auxiliary storage pool (ASP) of the library when the object was
saved.

IASP_NAME VARCHAR(10) The name of the independent auxiliary storage pool (ASP) device of the
library when the object was saved.

Member information

MEMBERS INTEGER The number of members saved for the file.


Contains the null value if DETAILED_INFO is NO or OUTQ or if
OBJECT_TYPE is not *FILE.

MEMBER_NAME VARCHAR(10) The name of the file member that was saved.
Contains the null value if DETAILED_INFO is NO or OUTQ or if
OBJECT_TYPE is not *FILE.

Spooled file information

SPOOLED_FILE_NAME VARCHAR(10) The name of the spooled file.


Contains the null value if DETAILED_INFO is NO or FILE or if
OBJECT_NAME is not an output queue.

SPOOLED_FILE_NUMBER INTEGER The number of the spooled file in the job that owns it.
Contains the null value if DETAILED_INFO is NO or FILE or if
OBJECT_TYPE is not *OUTQ.

QUALIFIED_JOB_NAME VARCHAR(28) The fully-qualified job name that owns the spooled file.
Contains the null value if DETAILED_INFO is NO or FILE or if
OBJECT_TYPE is not *OUTQ.

JOB_NAME VARCHAR(10) The name of the job that owns the spooled file.
Contains the null value if DETAILED_INFO is NO or FILE or if
OBJECT_TYPE is not *OUTQ.

JOB_USER VARCHAR(10) The name of the user who owns the spooled file.
Contains the null value if DETAILED_INFO is NO or FILE or if
OBJECT_TYPE is not *OUTQ.

540 IBM i: Performance and Query Optimization


Table 115. SAVE_FILE_OBJECTS table function (continued)

Column Name Data Type Description

JOB_NUMBER VARCHAR(6) The number of the job that owns the spooled file.
Contains the null value if DETAILED_INFO is NO or FILE or if
OBJECT_TYPE is not *OUTQ.

SYSTEM_NAME VARCHAR(8) The name of the system where the job that owns the spooled file ran.
Contains the null value if DETAILED_INFO is NO or FILE or if
OBJECT_TYPE is not *OUTQ.

CREATE_TIMESTAMP TIMESTAMP(0) The date and time when the spooled file was created.
Contains the null value if DETAILED_INFO is NO or FILE or if
OBJECT_TYPE is not *OUTQ.

Example
• List all the spooled files saved in the MYLIB/SAVF1 save file.

SELECT LIBRARY_NAME CONCAT '/' CONCAT OBJECT_NAME AS OUTPUT_QUEUE, SPOOLED_FILE_NAME,


SPOOLED_FILE_NUMBER, CREATE_TIMESTAMP
FROM TABLE (QSYS2.SAVE_FILE_OBJECTS(SAVE_FILE => 'SAVF1', SAVE_FILE_LIBRARY => 'MYLIB',
OBJECT_TYPE_FILTER => '*OUTQ', DETAILED_INFO => 'ALL'));

SAVE_FILE_OBJECTS view
The SAVE_FILE_OBJECTS view returns information about the objects in a save file. Information about
Integrated File System objects is not returned.
The SAVE_FILE_OBJECTS table function can be used to return detailed information about database file
(*FILE) members and output queue (*OUTQ) spooled files that were saved.
The information returned is similar to the detail available through the Display Save File (DSPSAVF) CL
command and the List Save File (QSRLSAVF) API.
Authorization: The caller must have:
• *USE authority to the library containing the save file, and
• *USE authority to the save file.
The following table describes the columns in the view. The system name is SAVF_OBJ. The schema is
QSYS2.
Table 116. SAVE_FILE_OBJECTS view

Column Name System Column Name Data Type Description

SAVE_FILE_LIBRARY SAVF_LIB VARCHAR(10) Name of the library that contains the save file.

SAVE_FILE SAVF VARCHAR(10) Name of the save file.

LIBRARY_NAME LIBNAME VARCHAR(10) The name of the library from which the object was
saved.

OBJECT_NAME NAME VARCHAR(10) The name of the saved object. Contains the system
name for a DLO object.

OBJECT_TYPE OBJ_TYPE VARCHAR(7) The type of object.

OBJECT_ATTRIBUTE OBJ_ATTR VARCHAR(10) Extended information about the object type.

Nullable Contains the null value if there is no object attribute.

TEXT_DESCRIPTION TEXT VARCHAR(50) The text description of the object.

Nullable Contains the null value if there is no text description.

SAVE_TIMESTAMP SAVED TIMESTAMP(0) The date and time at which the object was saved.

OBJECT_SIZE OBJ_SIZE BIGINT The size of the object, in bytes. This value will be a
rounded value for an object larger than 999,999,999
bytes.

Database performance and query optimization 541


Table 116. SAVE_FILE_OBJECTS view (continued)

Column Name System Column Name Data Type Description

DATA_SAVED DATA VARCHAR(3) Whether the data for this object was saved with the
object.

NO The data was not saved. The object's storage


was freed by a previous save command
before this save operation.

YES The data was saved. The object's storage was


not freed by a previous save command before
this save operation.

OBJECT_OWNER OBJ_OWNER VARCHAR(10) The owner of the object.

DLO_NAME DLO_NAME VARCHAR(20) The name of the document, folder, or mail object that
was saved.
Nullable
Contains the null value if there is no document library
object.

FOLDER_PATH FOLDER VARCHAR(63) The name of the folder that was saved.

Nullable Contains the null value if this is not a *FLR or *DOC


object, or if there is no folder path.

IASP_NUMBER IASPNUMBER INTEGER The auxiliary storage pool (ASP) of the library when
the object was saved.

IASP_NAME IASP_NAME VARCHAR(10) The name of the independent auxiliary storage pool
(ASP) device of the library when the object was
saved.

Example
• Find all the save files used to save any *FILE objects with names that begin with 'CUST'. Since this can
be a long-running query, submit it as a batch job. The RUNSQL CL command is used to run the SQL
statement and return the results in a table in MYLIB.

SBMJOB CMD(RUNSQL
SQL('CREATE TABLE MYLIB.SAVF_CUST AS (
SELECT SAVE_FILE_LIBRARY, SAVE_FILE, LIBRARY_NAME, OBJECT_NAME, SAVE_TIMESTAMP
FROM QSYS2.SAVE_FILE_OBJECTS
WHERE OBJECT_NAME LIKE ''CUST%'') WITH DATA')
COMMIT(*NONE)) JOB(SAVFLIST)

TAPE_CARTRIDGE_INFO view
The TAPE_CARTRIDGE_INFO view returns information about tape cartridges.
This information is similar to the information available through the Display Tape Cartridge (DSPTAPCTG)
CL command and the Retrieve Cartridge Information (QTARCTGI) API.
Authorization: The caller must have *USE authority to the device description.
The following table describes the columns in the view. If a device cannot be allocated to access its
information, a row containing only the device name is returned. The system name is TAPE_INFO. The
schema is QSYS2.
Table 117. TAPE_CARTRIDGE_INFO view

Column Name System Column Name Data Type Description

DEVICE_NAME DEVICE VARCHAR(10) The name of the tape library device.

CARTRIDGE_ID CTG_ID VARCHAR(6) The identifier of the cartridge.

CARTRIDGE_ID_SOURCE CTG_ID_SRC VARCHAR(9) The type of cartridge ID.

BAR CODE The cartridge ID was read from the bar code
label on the cartridge.

SYSTEM The cartridge ID is generated by the system.

VOLUME ID The volume identifier is used for the cartridge ID.

542 IBM i: Performance and Query Optimization


Table 117. TAPE_CARTRIDGE_INFO view (continued)

Column Name System Column Name Data Type Description

VOLUME_ID VOLUME_ID VARCHAR(6) The volume identifier for the cartridge that was read from the
tape volume labels. Can contain the following special value:
Nullable
*NL The volume is a non-labeled tape.

Contains the null value if the volume ID is not known.

MEDIA_TYPE MEDIA_TYPE VARCHAR(2) The media type read from the bar code label on the cartridge.

Nullable Contains the null value if the media type is not available.

CATEGORY CATEGORY VARCHAR(10) The category assigned to the cartridge.

CATEGORY_SYSTEM CAT_SYSTEM VARCHAR(8) The name of the system that owns the category assigned to the
cartridge.
Nullable
Contains the null value if the cartridge is assigned to a category
that does not have an owner.

STATUS STATUS VARCHAR(13) The status of the cartridge.

AVAILABLE The cartridge is available for use.

DUPLICATE The cartridge identifier exists more than once


in the library device. One of the cartridges
must be physically removed before the other
can be used in the library device.

EJECTED The cartridge ID is in the *EJECT category


or it was manually ejected from the library
device.

ERROR The status of the cartridge ID is unknown.


The cartridge cannot be found or is not in a
usable condition.

INSERTED The cartridge is inserted into the library. The


Add Tape Cartridge (ADDTAPCTG) command
must be issued to move the cartridge to
available status.

MOUNTED The cartridge is mounted in a tape device or


in the queue ready to be loaded.

NOT The cartridge is present but not available for


AVAILABLE use.

CHANGE_TIMESTAMP CHANGED TIMESTAMP(0) The timestamp when the cartridge was last used for output
operations.
Nullable
Contains the null value if a change timestamp is not available.

REFERENCE_TIMESTAMP REFERENCED TIMESTAMP(0) The timestamp the cartridge was last used for input or output
operations.
Nullable
Contains the null value if the cartridge has not been used.

LOCATION LOCATION VARCHAR(10) The current location of the cartridge. This can be either a slot
number or a tape resource name.
Nullable
Contains the null value if the cartridge is located in a storage slot
but the slot number is not known, or if the cartridge is located in
a tape drive but the drive location is not known.

LOCATION_INDICATOR LOC_IND VARCHAR(6) Where the tape cartridge is located.

*DRIVE The cartridge is located in a tape drive.

*SLOT The cartridge is located in a storage slot.

OWNER_ID OWNER_ID VARCHAR(17) The owner ID specified when the tape was initialized. This
information is read from the tape volume labels. Can contain
Nullable the following special values:

*BLANK The owner ID in the tape labels is blank.

*NL The cartridge is a non-labeled tape.

Contains the null value if the owner ID is not known.

Database performance and query optimization 543


Table 117. TAPE_CARTRIDGE_INFO view (continued)

Column Name System Column Name Data Type Description

DENSITY DENSITY VARCHAR(10) The last known cartridge density.

Nullable Contains the null value if the density is not known.

WRITE_PROTECTED PROTECTED VARCHAR(3) Whether the cartridge is write protected.

Nullable NO The cartridge is not write protected.

YES The cartridge is write protected.

Contains the null value if the cartridge write protect status is not
known.

ENCODING ENCODING VARCHAR(6) The encoding of the tape volume. The encoding of a tape volume
is determined when the Initialize Tape (INZTAP) command is
Nullable used.

ASCII ASCII encoding is used.

EBCDIC EBCDIC encoding is used.

Contains the null value if the encoding is not known.

IMPORT_EXPORT_SLOT IMP_EXP VARCHAR(3) Whether the cartridge is in an Import/Export slot.

NO The cartridge is not in an import/export slot.

YES The cartridge is in an import/export slot.

Example
Return information about all tape cartridges that do not currently have a status of AVAILABLE.

SELECT * FROM QSYS2.TAPE_CARTRIDGE_INFO


WHERE STATUS <> 'AVAILABLE';

Communication Services
These services provide communication information.

ACTIVE_DB_CONNECTIONS table function


The ACTIVE_DB_CONNECTIONS table function returns a result table that contains one row for each
DRDA, DDM, and Db2 Mirror connection. For these connections, the specified job has either an application
requester or application server role.
If a connection is no longer active on the remote system, it might still appear in the result of this table
function. For this situation, the ERROR column will have a value of YES.
Authorization: The caller must be the same user profile that is running the specified job-name,
or the caller must have *JOBCTL special authority, or be authorized to the QIBM_DB_SQLADM or
QIBM_DB_SYSMON function usage identifier.

ACTIVE_DB_CONNECTIONS ( job-name )
JOB_NAME =>

The schema is QSYS2.

job-name An expression that contains the qualified job name for which connection information is to be
returned. The special value of '*' indicates the current job.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.

544 IBM i: Performance and Query Optimization


Table 118. ACTIVE_DB_CONNECTIONS table function

Column Name Data Type Description

CONNECTION_USAGE VARCHAR(21) The connection usage of the local server (job-name) side of
the connection.

APPLICATION The remote job is the application


REQUESTER requester, often called the client.

APPLICATION The remote job is the application


SERVER server, often called the server.

REMOTE_HOST_NAME VARCHAR(255) The name of the remote system for this connection.

REMOTE_JOB_NAME VARCHAR(28) The qualified job name of the remote job that is connected
to job-name.
Contains the null value if the remote server is not an IBM i.

REMOTE_USER VARCHAR(255) User name for the remote connection.

CLIENT_RDB VARCHAR(18) The RDB name of the application requester.


Can contain the null value if the connection is only used for a
DDM file operation.

SERVER_RDB VARCHAR(18) The RDB name of the application server.


Can contain the null value if the connection is only used for a
DDM file operation.

CONNECTION_TIME TIMESTAMP Timestamp for when the connection was established.

CONNECTION_TIME_UTC TIMESTAMP Timestamp for when the connection was established, in


Universal Time Coordinated (UTC).

CONNECTION_TYPE VARCHAR(11) The type of connection established between job-name and


REMOTE_JOB_NAME.

DB2 MIRROR This connection is a Db2 Mirror


connection.

OPTICONNECT This connection is an OptiConnect


connection.

SNA This connection is an SNA connection.

TCP/IP This connection is a TCP/IP connection.

NRG_NAME VARCHAR(15) The Network Redundancy Group (NRG) used for this
connection.
Contains the null value if CONNECTION_TYPE is not DB2
MIRROR.

CLIENT_PORT INTEGER The client host port number.

CLIENT_ADDRESS VARCHAR(45) IP address of the client. This is shown in IPv6 address


format.

SERVER_PORT INTEGER The server host port number.

SERVER_ADDRESS VARCHAR(45) IP address of the server. This is shown in IPv6 address


format.

SNA_DEVICE_NAME VARCHAR(10) The name of the device used to communicate with the
remote location.
Contains the null value if CONNECTION_TYPE is not SNA.

SNA_MODE_NAME VARCHAR(8) The name of the mode to be used to communicate between


the local location and remote location.
Contains the null value if CONNECTION_TYPE is not SNA.

SNA_LOCAL_LOCATION_NAME VARCHAR(8) Indicates the local location name by which this system is
identified to the system on which the RDB is located.
Contains the null value if CONNECTION_TYPE is not SNA.

SNA_REMOTE_LOCATION_NAME VARCHAR(8) The name of the remote location where the remote file
exists.
Contains the null value if CONNECTION_TYPE is not SNA.

Database performance and query optimization 545


Table 118. ACTIVE_DB_CONNECTIONS table function (continued)

Column Name Data Type Description

SNA_REMOTE_NETWORK_ID VARCHAR(8) Indicates the remote network identifier of the system on


which the RDB is located.
Contains the null value if CONNECTION_TYPE is not SNA.

SNA_TRANSACTION_PROGRAM_ VARCHAR(19) Indicates the transaction program name (TPN) specified in


NAME the RDB directory entry. The value is returned as a hex string
in the form X'aabbcc'.
Contains the null value if CONNECTION_TYPE is not SNA.

SSL VARCHAR(3) Indicates whether this connection uses SSL.

NO The connection does not use SSL.

YES The connection uses SSL.

THREE_PART_NAMING VARCHAR(3) Indicates whether this connection was established using an


SQL statement with 3-part naming.

NO This connection was not established using an SQL


statement with 3-part naming.

YES This connection was established using an SQL


statement with 3-part naming.

Contains the null value if CONNECTION_USAGE is


APPLICATION SERVER.

XA VARCHAR(3) Indicates whether this connection is used for XA.

NO This is not an XA connection.

YES This is an XA connection.

Contains the null value if CONNECTION_USAGE is


APPLICATION SERVER.

ACTIVATION_GROUP_NUMBER BIGINT Activation group number for job making the connection.
Contains the null value if CONNECTION_USAGE is
APPLICATION SERVER.

ACTIVATION_GROUP_NAME VARCHAR(10) Activation group name for job making the connection.
Contains the null value if the activation group has no name
or if CONNECTION_USAGE is APPLICATION SERVER.

THREAD_ID BIGINT The thread ID for the connection.


Contains the null value if CONNECTION_USAGE is
APPLICATION SERVER.

SCOPE VARCHAR(16) Scope of the connection.

ACTIVATION The connection is scoped to the


GROUP activation group.

JOB The connection is scoped to the job.

Contains the null value if CONNECTION_USAGE is


APPLICATION SERVER.

COMMIT_PROTOCOL VARCHAR(9) The commitment control protocol used for this connection.

ONE-PHASE The connection uses one-phase


commitment control.

TWO-PHASE The connection uses two-phase


commitment control.

Contains the null value if CONNECTION_USAGE is


APPLICATION SERVER.

REMOTE_CLASS VARCHAR(255) The class of the remote server.


Some common values are:

QAS Db2 for i

QDB2 Db2 for z/OS®

QDB2/xxx Db2 for LUW

546 IBM i: Performance and Query Optimization


Table 118. ACTIVE_DB_CONNECTIONS table function (continued)

Column Name Data Type Description

REMOTE_RELEASE VARCHAR(255) The release level of the remote server.

ERROR VARCHAR(3) Indicates whether the connection is currently in an error


state. For example, a communication failure occurred.

NO The connection is not in an error state.

YES The connection is in an error state.

SUSPEND_PROCESSING_START TIMESTAMP The timestamp, in Universal Time Coordinated (UTC),


when the most recent Db2 Mirror suspend state change
processing started for this job. The timestamp is not cleared
when the state change processing is complete.
Contains the null value if no prior suspend state change has
occurred for this job.

SUSPEND_PROCESSING_END TIMESTAMP The timestamp, in Universal Time Coordinated (UTC),


when the most recent Db2 Mirror suspend state change
processing ended for this job. The timestamp is not cleared
when the state change processing is complete.
Contains the null value if no prior suspend state change has
occurred for this job.

Example
• List all the connections that are active for a specific job.

SELECT * FROM TABLE (QSYS2.ACTIVE_DB_CONNECTIONS('900239/SKALSKY/QPADEV000F'));

ADD_TIME_SERVER procedure
The ADD_TIME_SERVER procedure adds a Network Time Protocol (NTP) server to the NTP configuration
list.
The ADD_TIME_SERVER procedure requires 5770SS1 Option 33 - Portable Application Solutions
Environment (PASE).
Authorization: The caller must have:
• *IOSYSCFG special authority, and
• *RW authority to /QIBM/UserData/OS400/TCPIP/NTP/ntp.conf

ADD_TIME_SERVER ( time-server
TIME_SERVER =>

, preferred-indicator )
PREFERRED_INDICATOR =>

The schema is QSYS2.

time-server A character or graphic string that identifies the DNS name of the NTP server to be
added to the configuration.
preferred- A character or graphic string that indicates whether this NTP server should be
indicator considered a preferred time server.

NO This is not a preferred time server.


YES This is a preferred time server.

Example

Database performance and query optimization 547


• Add time.domain.name.com as a preferred time server

CALL QSYS2.ADD_TIME_SERVER(TIME_SERVER =>'time.domain.name.com',


PREFERRED_INDICATOR => 'YES');

CHANGE_OBJECTCONNECT procedure
The CHANGE_OBJECTCONNECT procedure changes, starts, or stops the ObjectConnect over IP server.
The procedure is similar to the Change ObjectConnect Attrs (CHGOBJCA) CL command.
If the subsystem description parameter is changed while the ObjectConnect over IP server is running, the
change takes effect the next time the server is restarted.
This procedure requires that Option 22 of the IBM i operating system is installed.
Authorization: The caller must have *IOSYSCFG special authority.
The caller must have *USE authority to the QSYS/STRTCPSVR command when changing STATE to 'START'.
The caller must have *USE authority to the QSYS/ENDTCPSVR command when changing STATE to 'END'.
The caller must have additional authority when changing SUBSYSTEM_DESCRIPTION_LIBRARY or
SUBSYSTEM_DESCRIPTION.
• The caller must have *READ, *ADD, and *EXECUTE authorities to the library containing the subsystem
description.
• If the subsystem description does not exist, the caller must have *USE authority to the QSYS/CRTSBSD
CL command.
• If the subsystem description exists, the caller must have *READ, *OBJMGT and *OBJOPR authorities to
the subsystem description.
• If the job queue referenced by the subsystem description exists, the caller must have *READ, *OBJMGT
and *OBJOPR authorities to the job queue.
If the subsystem description and job queue exist, the QOBJC user profile will be granted *USE authority to
these objects.

548 IBM i: Performance and Query Optimization


CHANGE_OBJECTCONNECT (
state
STATE =>

, auto-start
AUTO_START =>

, minimum-jobs
MINIMUM_JOBS =>

, maximum-jobs
MAXIMUM_JOBS =>

, inactive-time
INACTIVE_TIME =>

, send-buffer
SEND_BUFFER =>

, receive-buffer
RECEIVE_BUFFER =>

, subsystem-description-library
SUBSYSTEM_DESCRIPTION_LIBRARY =>

, subsystem-description
SUBSYSTEM_DESCRIPTION =>

)
, authentication-type
AUTHENTICATION_TYPE =>

The schema is QSYS2.

state A character or graphic string that indicates how to change the state of the
ObjectConnect over IP server. If this parameter is omitted, the state of the
ObjectConnect over IP server does not change.

END End the ObjectConnect over IP server.


START Start the ObjectConnect over IP server.

auto-start A character or graphic string that indicates how to start the ObjectConnect over IP
server. If this parameter is omitted, the auto start setting does not change. The initial
configuration default value is YES.

NO Do not start the ObjectConnect over IP server automatically.

Database performance and query optimization 549


YES Start the ObjectConnect over IP server automatically.

minimum-jobs An integer value that specifies the minimum number of server jobs that are started
by the ObjectConnect receiver job to accept client connections. If this parameter
is omitted, the minimum number of server jobs does not change. The initial
configuration default value is 1 and the maximum value is 999.
maximum-jobs An integer value that specifies the maximum number of server jobs that are started
by the ObjectConnect receiver job to accept client connections. If this parameter
is omitted, the maximum number of server jobs does not change. The initial
configuration default value is 5 and the maximum value is 32767.
inactive-time An integer value that specifies the length of time in minutes a server job will stay
inactive before ending. If this parameter is omitted, the server inactive time does not
change. The initial configuration default value is 30 and the maximum value is 1440.
send-buffer An integer value that specifies the size of the TCP send buffer, in bytes, that the
data connection will use to send data over the network. If this parameter is omitted,
the TCP send buffer size does not change. The initial configuration default value is
262144, the minimum value is 512 and maximum value is 8388608.
receive-buffer An integer value that specifies the size of the TCP receive buffer, in bytes, that
the data connection will use to receive data from the network. If this parameter is
omitted, the TCP receive buffer size does not change. The initial configuration default
value is 8388608, the minimum value is 512 and maximum value is 8388608.
subsystem- A character or graphic string that contains the library name where subsystem-
description- description resides. The library can be QSYS for IBM shipped subsystem QUSRWRK
library or any user library. The library must exist. If this parameter is omitted, the subsystem
library does not change.
subsystem- A character or graphic string that indicates the subsystem where the ObjectConnect
description server will run in. The subsystem can be IBM shipped subsystem QSYS/QUSRWRK or
a user-provided subsystem description. When the subsystem-description parameter
is provided, the subsystem-description-library parameter must also be provided.
If the user-provided subsystem description exists, the QOBJC user profile will be
granted *USE authority to the object. If the subsystem description does not exist,
it will be created along with a job queue having same name. If this parameter is
omitted, the subsystem does not change. The initial configuration default value is
QSYS/QUSRWRK.
authentication- A character or graphic string that indicates which authentication type can be used
type by the ObjectConnect over IP server to authenticate the incoming ObjectConnect
connection request. If this parameter is omitted, the authentication type does not
change. The initial configuration default value is ANY.

ANY The ObjectConnect over IP server can use any of the supported
authentication types to authenticate an incoming ObjectConnect
connection request.
KERBEROS The ObjectConnect over IP server can use Kerberos to authenticate
an incoming ObjectConnect connection request.
PASSWORD The ObjectConnect over IP server can use the user profile and
password to authenticate an incoming ObjectConnect connection
request.

Example
• Start the ObjectConnect over IP server.

550 IBM i: Performance and Query Optimization


CALL QSYS2.CHANGE_OBJECTCONNECT(STATE => 'START');

DNS_LOOKUP table function


The DNS_LOOKUP table function queries a domain name server for IP address information about a
hostname.
Authorization: If the HOSTALIASES environment variable is set, the caller must have:
• Execute (*X) data authority to each directory in the path of the host aliases file specified by the
HOSTALIASES environment variable, and
• Read (*R) data authority to the host aliases file.

DNS_LOOKUP ( search-name
SEARCH_NAME =>

)
, domain-server
DOMAIN_SERVER =>

The schema is QSYS2.

search-name A character string containing the fully qualified domain name of the host to be resolved.
domain-server A character string containing either a host name or an IP address for the domain name
server, or an IP address string for it.
If this parameter is omitted, the IPv4 or IPv6 configured name servers from
CHGTCPDMN are used.

The result of the function is a table containing rows with the format shown in the following table. All
columns are nullable.
Table 119. DNS_LOOKUP table function

Column Name Data Type Description

ADDRESS_SPACE_TYPE CHAR(4) The IP address space type for IP_ADDRESS

IPV4 The address is specified using the IPv4 address space type.

IPV6 The address is specified using the IPv6 address space type.

IP_ADDRESS VARCHAR(45) The IP address. When ADDRESS_SPACE_TYPE is IPV4, the address is


in IPv4 format. When ADDRESS_SPACE_TYPE is IPV6, the address is
in IPv6 format.

AUTHORITATIVE VARCHAR(3) Indicates whether the DNS response containing the IP address was an
authoritative answer.

NO The DNS response was a non-authoritative answer.

YES The DNS response was an authoritative answer.

AUTHENTICATED_DATA VARCHAR(3) Whether the data was authenticated.

NO Data was not DNSSEC authenticated

YES Data was DNSSEC authenticated.

Example
• Determine the IP address for the ibm.com® hostname.

SELECT * FROM TABLE(QSYS2.DNS_LOOKUP('ibm.com'));

Database performance and query optimization 551


DNS_LOOKUP_IP scalar function
The DNS_LOOKUP_IP scalar function returns a hostname for a specified IP address.
Authorization: None required.

DNS_LOOKUP_IP ( ip-address )
IP_ADDRESS =>

The schema is QSYS2.

ip-address A character string containing the IP address to be resolved to a hostname. The IP address
can be in either IPv4 or IPv6 format.

The result of the function is a varying length character string that contains the corresponding hostname. If
a hostname cannot be determined, the null value is returned.

Example
• Determine the hostname for IP address 129.42.38.10. The result is ibm.com.

VALUES QSYS2.DNS_LOOKUP_IP('129.42.38.10');

ENV_SYS_INFO view
The ENV_SYS_INFO view contains information about the current server.
Authorization: None required.
The following table describes the columns in the view. The system name is ENVSYSINFO. The schema is
SYSIBMADM.
Table 120. ENV_SYS_INFO view

Column Name System Column Name Data Type Description

OS_NAME OS_NAME VARCHAR(256) Operating system name.

Nullable

OS_VERSION OS_VERSION VARCHAR(256) Operating system version.

Nullable

OS_RELEASE OS_RELEASE VARCHAR(256) Operating system release.


Nullable

HOST_NAME HOST_NAME VARCHAR(256) Name of the system.

Nullable

TOTAL_CPUS TOTAL_CPUS INTEGER The maximum number of virtual processors defined within the
LPAR configuration.
Nullable

CONFIGURED_CPUS CONFIGCPUS INTEGER The number of virtual processors currently available to the
partition.
Nullable

CONFIGURED_MEMORY CONFIGMEM BIGINT Total amount of configured memory on the system, in


megabytes.
Nullable

TOTAL_MEMORY TOTAL_MEM INTEGER Total amount of memory on the system, in megabytes.

Nullable

Example

552 IBM i: Performance and Query Optimization


Return information about the current server.

SELECT * FROM SYSIBMADM.ENV_SYS_INFO

HTTP_SERVER_INFO view
The HTTP_SERVER_INFO view returns information for HTTP Server for IBM i (powered by Apache). Only
information for enabled and active functions is returned.
The values returned for the result columns of the table function are similar to the values shown by Real
Time Server Statistics in the IBM Web Administration for i GUI.
Authorization: None required.
The following table describes the columns in the view. The system name is HTTP_SRVR. The schema is
QSYS2.
Table 121. HTTP_SERVER_INFO view

Column Name System Column Name Data Type Description

SERVER_NAME SERVER VARCHAR(10) The name of the HTTP server instance.

JOB_NAME JOB_NAME VARCHAR(28) Qualified job name for the server.

SERVER_START_TIME START_T TIMESTAMP(0) Time the server was started.

SERVER_RESTART_TIME RESTART_T TIMESTAMP(0) Time the server was restarted.

Nullable Contains the null value if the server has never


been restarted.

SERVER_CURRENT_TIME CURRENT_T TIMESTAMP(0) Current time.

SERVER_NORMAL_CONNECTIONS NORM_CONN BIGINT Total number of normal (non-secure) connections


to the server.

SERVER_SSL_CONNECTIONS SSL_CONN BIGINT Total number of SSL (secure) connections to the


server.

SERVER_ACTIVE_THREADS ACT_THRD INTEGER Number of active threads.

SERVER_IDLE_THREADS IDLE_THRD INTEGER Number of idle threads.

SERVER_TOTAL_REQUESTS TOT_REQ BIGINT Total number of requests to the server since the
server was started.

SERVER_TOTAL_REQUESTS_REJECTED TOT_REQREJ BIGINT Total number of rejected requests issued by the


server since the server was started.

SERVER_TOTAL_RESPONSES TOT_RESP BIGINT Total number of responses from the server since
the server was started.

Database performance and query optimization 553


Table 121. HTTP_SERVER_INFO view (continued)

Column Name System Column Name Data Type Description

HTTP_FUNCTION HTTP_FUNC VARCHAR(20) HTTP server function or associated server for the
remaining statistical information columns. A row
is only returned for a function if the function is
enabled.

CGI Common Gateway


Interface (CGI)

CUSTOMER A customer or third-party


MODULE module

FRCA PROXY Fast Response Cache


Accelerator (FRCA) proxy

FRCA STATS Fast Response Cache


Accelerator (FRCA)

PROXY Proxy

SERVER Server transactions. This


HANDLED includes static HTML
pages, HTML pages
containing Server Side
Includes (SSI), and images.

SSL Secure Sockets Layer (SSL)

WEBSPHERE WebSphere Application


Server

REQUESTS REQUESTS BIGINT Number of requests received.

RESPONSES RESPONSES BIGINT Number of responses sent.

ERROR_RESPONSES ERR_RESP BIGINT Number of error responses.

NONCACHE_RESPONSES NC_RESP BIGINT Number of responses that did not come from
cache.

BYTES_RECEIVED BYTES_RCV BIGINT Total number of bytes received for all requests.

BYTES_SENT BYTES_SENT BIGINT Total number of bytes sent for all requests.

NONCACHE_PROCESSING_TIME NC_TIME DECIMAL(20,3) Processing time for non-cached requests, in


seconds.

CACHE_PROCESSING_TIME C_TIME DECIMAL(20,3) Processing time for cached requests, in seconds.

Example
• Examine information about the server functions associated with the ADMIN server.

SELECT * FROM QSYS2.HTTP_SERVER_INFO


WHERE SERVER_NAME = 'ADMIN';

NETSTAT_INFO view
The NETSTAT_INFO view returns information about IPv4 and IPv6 network connections.
The values returned for the columns in the view are closely related to the values returned by List
Network Connections API and Retrieve Network Connection Data API. Refer to the APIs for more detailed
information.
Authorization: None required.
The following table describes the columns in the view. The system name is NS_INFO. The schema is
QSYS2.

554 IBM i: Performance and Query Optimization


Table 122. NETSTAT_INFO view

Column Name System Column Name Data Type Description

CONNECTION_TYPE CONN_TYPE CHAR(4) The type of connection.

IPV4 The connection is an IPv4 connection.

IPV6 The connection is an IPv6 connection.

REMOTE_ADDRESS RMT_ADDR VARCHAR(45) The internet address of the remote host.


For IPv4:
• The address is in IPv4 address format. A value of 0.0.0.0
indicates that either the system is waiting for a connection to
open or that a UDP socket is being used. A value of 0 means
that the connection is a listening or UDP socket so this field
does not apply.
For IPv6:
• The address is in IPv6 address format. A value of :: means that
the connection is a listening socket so this field does not apply.

REMOTE_PORT RMT_PORT INTEGER The remote host port number. A value of 0 means that the
connection is a listening or UDP socket, so this field does not
apply.

REMOTE_PORT_NAME RMT_NAME VARGRAPHIC(14) The remote host well-known port name or the name from the
CCSID 1200 service table entry.

Nullable Contains null if there is no well-known port name.

LOCAL_ADDRESS LOCAL_ADDR VARCHAR(45) The local address of this connection on this system.
For IPv4:
• The address is in IPv4 address format. A value of 0.0.0.0
indicates that either the system is waiting for a connection to
open or that a UDP socket is being used.
For IPv6:
• The address is in IPv6 address format. A value of :: means the
local application specified that any local internet address can
be used.

LOCAL_PORT LOCAL_PORT INTEGER The local system port number.

LOCAL_PORT_NAME LOCAL_NAME VARGRAPHIC(14) The local system well-known port name or the name from the
CCSID 1200 service table entry.

Nullable Contains null if there is no well-known port name.

PROTOCOL PROTOCOL VARCHAR(3) Identifies the type of connection protocol.

TCP A Transmission Control Protocol (TCP) connection or


socket.

UDP A User Datagram Protocol (UDP) socket.

Database performance and query optimization 555


Table 122. NETSTAT_INFO view (continued)

Column Name System Column Name Data Type Description

TCP_STATE STATE VARCHAR(12) The state of the connection.

Nullable CLOSED This connection has ended.

CLOSE-WAIT Waiting for an end connection request from


the local user.

CLOSING Waiting for an end connection request


acknowledgment from the remote host.

ESTABLISHED The normal state in which data is transferred.

FIN-WAIT-1 Waiting for the remote host to acknowledge


the local system request to end the
connection.

FIN-WAIT-2 Waiting for the remote host request to end


the connection.

LAST-ACK Waiting for the remote host to acknowledge


an end connection request.

LISTEN Waiting for a connection request from any


remote host.

SYN-RECEIVED Waiting for a confirming connection request


acknowledgment.

SYN-SENT Waiting for a matching connection request


after having sent a connection request.

TIME-WAIT Waiting to allow the remote host enough


time to receive the local system's
acknowledgment to end the connection.

Contains null if PROTOCOL is UDP.

IDLE_TIME IDLE_TIME DECIMAL(19,3) The length of time, in seconds, since the last activity on this
connection.

BIND_USER BIND_USER VARCHAR(10) The user profile of the job on the local system which first
performed a sockets API bind() of the socket.

BYTES_SENT_REMOTELY BYTES_OUT BIGINT The number of bytes sent to the remote host.

BYTES_RECEIVED_LOCALLY BYTES_IN BIGINT The number of bytes received from the remote host.

NETWORK_CONNECTION_TYPE NET_TYPE VARCHAR(4) The type of connection or socket.

*TCP Identifies a transmission control protocol (TCP)


connection socket.

*UDP Identifies a User Datagram Protocol (UDP) socket.

For IPv4, the following additional value can be returned.

*IPS Identifies an Internet Protocol (IP) over SNA connection


or socket.

CONNECTION_OPEN_TYPE OPN_TYPE VARCHAR(7) The type of open for the connection.

Nullable ACTIVE The local system opens the connection.

PASSIVE A remote host opens the connection.

Contains null if PROTOCOL is UDP.

NUMBER_OF_ASSOCIATED_JOBS NUM_JOBS INTEGER The number of jobs associated with this connection.

LINE_DESCRIPTION LINE_DES VARCHAR(10) The local system line description associated with this connection.

Nullable Contains null if this is an IPv4 connection or if the connection is


not bound to a link local unicast interface.

VIRTUAL_LAN_ID LAN_ID VARCHAR(4) The virtual LAN identifier associated with this connection. Can
also contain the following special value:
Nullable
NONE No virtual LAN identifier is associated with this
connection.

Contains null if this is an IPv4 connection or if the connection is


not bound to a link local unicast interface.

556 IBM i: Performance and Query Optimization


Table 122. NETSTAT_INFO view (continued)

Column Name System Column Name Data Type Description

CONNECTION_TRANSPORT_ CNNTRANSPT VARCHAR(5) The transport that a connection is using. Values are:
LAYER • IPS
• TCPIP

IP_OPTIONS IP_OPTIONS BINARY(40) The hex value of IP datagram options that may have been
specified for a connection.
Nullable
Contains null if this is an IPv6 connection or if no IP datagram
options have been specified.

ROUND_TRIP_TIME ROUND_TRIP BIGINT The smoothed round-trip time interval in milliseconds. This is a
measure of the time required for a segment on the connection
Nullable to arrive at its destination, to be processed, and to return an
acknowledgment to the client.
Contains null if PROTOCOL is UDP.

ROUND_TRIP_VARIANCE ROUND_VAR BIGINT The variance in milliseconds from the previous round-trip time.

Nullable Contains null if PROTOCOL is UDP.

CURRENT_RETRANSMISSIONS CT_RETRANS BIGINT The number of times the local system retransmitted the current
segment without receiving an acknowledgment.
Nullable
Contains null if PROTOCOL is UDP.

TOTAL_RETRANSMISSIONS TL_RETRANS BIGINT The total number of times the local system retransmitted a
segment because an acknowledgement was not received. This is
Nullable a cumulative count of all segments resent during the entire time
the connection has been active.
Contains null if PROTOCOL is UDP.

TCP_CONNECTIONS_ TCPCONN BIGINT The number of TCP connections for which the current state is
CURRENTLY_ESTABLISHED either ESTABLISHED or CLOSE-WAIT.
Nullable
Contains null if PROTOCOL is UDP.

TCP_ACTIVE_OPENS TCPACTOPN BIGINT The number of times TCP connections have made a direct
transition to the SYN-SENT state from the CLOSED state. This
Nullable number is an indication of the number of times this local system
opened a connection to a remote system.
Contains null if PROTOCOL is UDP.

TCP_PASSIVE_OPENS TCPPSVOPN BIGINT The number of times TCP connections have made a direct
transition to the SYN-RECEIVED state from the LISTEN state. This
Nullable number is an indication of the number of times a remote system
opened a connection to this system.
Contains null if PROTOCOL is UDP.

TCP_FAILED_OPENS TCPFAILOPN BIGINT The total number of times TCP connections have made direct
transitions to a CLOSED state from either the SYN-SENT state or
Nullable the SYN-RECEIVED state and/or to LISTEN from SYN-RECEIVED.
Contains null if PROTOCOL is UDP.

TCP_ESTABLISHED_AND_THEN_ TCPESTRST BIGINT The number of times TCP connections have made a direct
RESET transition to the CLOSED state from either the ESTABLISHED
Nullable state or the CLOSE-WAIT state.
Contains null if PROTOCOL is UDP.

TCP_SEGMENTS_SENT TCPSEGSENT BIGINT The total number of segments sent, including those on current
connections but excluding those containing only retransmitted
Nullable octets.
Contains null if PROTOCOL is UDP.

TCP_SEGMENTS_ TCPSEGRTRN BIGINT The number of TCP segments transmitted containing one or more
RETRANSMITTED previously transmitted octets.
Nullable
Contains null if PROTOCOL is UDP.

TCP_SEGMENTS_RESET TCPSEGRST BIGINT The number of TCP segments sent containing the RST flag.

Nullable Contains null if PROTOCOL is UDP.

Database performance and query optimization 557


Table 122. NETSTAT_INFO view (continued)

Column Name System Column Name Data Type Description

TCP_SEGMENTS_RECEIVED TCPSEGRCV BIGINT The total number of segments received, including those received
in error. This count includes segments received on currently
Nullable established connections.
Contains null if PROTOCOL is UDP.

TCP_SEGMENTS_RECEIVED_ TCPSEGRCVE BIGINT The total number of segments received in error (for example, bad
ERROR TCP checksums).
Nullable
Contains null if PROTOCOL is UDP.

OUTGOING_BYTES_BUFFERED BYTES_OUTB BIGINT The current number of bytes that an application has requested to
send, but TCP has not yet sent. If TCP has sent the bytes to the
Nullable remote system but has not yet received an acknowledgment, the
bytes are considered 'not sent'. They are included in this count.
Contains null if PROTOCOL is UDP.

USER_SEND_NEXT USRSNDNXT BIGINT The sequence number of the next byte of data to be sent by the
client application.
Nullable
Contains null if PROTOCOL is UDP.

SEND_NEXT SEND_NEXT BIGINT The sequence number of the next byte of data that the local TCP
application sends to the remote TCP application.
Nullable
Contains null if PROTOCOL is UDP.

SEND_UNACKNOWLEDGED SNDUNACK BIGINT The sequence number of the last segment sent that was not
acknowledged. This is the smallest sequence number of the send
Nullable window.
Contains null if PROTOCOL is UDP.

OUTGOING_PUSH_NUMBER OUTPSHNBR BIGINT The sequence number of the last byte of push data in the
outgoing stream. This value is zero if no push data is in the
Nullable outgoing data stream.
Contains null if PROTOCOL is UDP.

OUTGOING_URGENCY_NUMBER OUTURGNBR BIGINT The sequence number of the last byte of urgent data in the
outgoing data stream. This value is zero if no urgent data is in
Nullable the outgoing data stream.
Contains null if PROTOCOL is UDP.

OUTGOING_WINDOW_NUMBER OUTWINNBR BIGINT The largest sequence number in the send window of the
connection. The local TCP application cannot send data bytes
Nullable with sequence numbers greater than the outgoing window
number.
Contains null if PROTOCOL is UDP.

INCOMING_BYTES_BUFFERED BYTES_INB BIGINT The current number of bytes that are received and buffered by
TCP. These bytes are available to be read by an application.
Nullable
Contains null if PROTOCOL is UDP.

RECEIVE_NEXT RCVNEXT BIGINT The next sequence number the local TCP is expecting to receive.

Nullable Contains null if PROTOCOL is UDP.

USER_RECEIVE_NEXT USRRCVNXT BIGINT The sequence number of the next byte to be passed to the
application by TCP.
Nullable
Contains null if PROTOCOL is UDP.

INCOMING_PUSH_NUMBER INPSHNBR BIGINT The sequence number of the last byte of pushed data in the
incoming data stream. This value is zero if no push data is in the
Nullable incoming data stream.
Contains null if PROTOCOL is UDP.

INCOMING_URGENCY_NUMBER INURGNBR BIGINT The sequence number of the last byte of urgent data in the
incoming data stream. This value is zero if no urgent data is in
Nullable the incoming data stream.
Contains null if PROTOCOL is UDP.

INCOMING_WINDOW_NUMBER INWINNBR BIGINT The largest sequence number in the incoming window of this
connection. Data bytes in the incoming stream having sequence
Nullable numbers larger than this number are not accepted.
Contains null if PROTOCOL is UDP.

558 IBM i: Performance and Query Optimization


Table 122. NETSTAT_INFO view (continued)

Column Name System Column Name Data Type Description

MAXIMUM_WINDOW_SIZE MAXWINSIZ BIGINT The largest size of the send window, in bytes, during the entire
time the connection has been active.
Nullable
Contains null if PROTOCOL is UDP.

CURRENT_WINDOW_SIZE CURWINSIZ BIGINT The current send window size in bytes.

Nullable Contains null if PROTOCOL is UDP.

LAST_UPDATE LSTUPD BIGINT The sequence number of the incoming segment used for the last
window update that occurred on the connection.
Nullable
Contains null if PROTOCOL is UDP.

LAST_UPDATE_ACKNOWLEDGED LSTUPDACK BIGINT The acknowledgment number of the incoming segment used for
the last window update that occurred on the connection.
Nullable
Contains null if PROTOCOL is UDP.

CONGESTION_WINDOW CONGESTWIN BIGINT The number of segments that are sent on the next transmission.
If an acknowledgment is received, the number is increased. If
Nullable an acknowledgment is not received, the number is reset to the
smallest allowable number.
Contains null if PROTOCOL is UDP.

SLOW_START_THRESHOLD SLWSTRTHR BIGINT The value of the slow-start threshold.

Nullable Contains null if PROTOCOL is UDP.

MAXIMUM_SEGMENT_SIZE MAXSEGSIZ BIGINT The size in bytes of the largest segment that may be transmitted
on this connection.
Nullable
Contains null if PROTOCOL is UDP.

INITIAL_SEND_SEQUENCE_ SNDSEQNBR BIGINT The first sequence number sent on this connection.
NUMBER Nullable Contains null if PROTOCOL is UDP.

INITIAL_RECEIVE_SEQUENCE_ RCVSEQNBR BIGINT The first sequence number received on this connection.
NUMBER Nullable Contains null if PROTOCOL is UDP.

UDP_DATAGRAMS_SENT UDPSENT BIGINT The total number of UDP datagrams sent from all connections
since TCP/IP was started.
Nullable
Contains null if PROTOCOL is TCP.

UDP_DATAGRAMS_RECEIVED UDPRCV BIGINT The total number of UDP datagrams received, including those
received in error. This count includes datagrams received on
Nullable currently established connections.
Contains null if PROTOCOL is TCP.

UDP_DATAGRAMS_NOT_ UDPNDPNF BIGINT The total number of received UDP datagrams for UDP users for
DELIVERED_PORT_ which there was no application at the destination port.
Nullable
NOT_FOUND Contains null if PROTOCOL is TCP.

UDP_DATAGRAMS_NOT_ UDPNDOTHER BIGINT The number of received UDP datagrams that could not be
DELIVERED_OTHER delivered for reasons other than the lack of an application at the
Nullable destination port.
Contains null if PROTOCOL is TCP.

SOCKET_STATE SOCSTATE VARCHAR(13) The current state of the socket. Values are:
• BOUND
• CONNECTED
• CONNECTING
• DISCONNECTED
• ERROR
• LISTENING
• UNBOUND
• UNINITIALIZED

Database performance and query optimization 559


Table 122. NETSTAT_INFO view (continued)

Column Name System Column Name Data Type Description

SOCKET_BROADCAST SOCBROAD VARCHAR(3) Indicates if messages can be sent to the broadcast address.

Nullable NO Messages cannot be sent to the broadcast address.

YES Messages can be sent to the broadcast address.

Contains null if value is not specified or if socket is not an address


family of AF_INET and type SOCK_DGRAM or SOCK_RAW.

SOCKET_BYPASS_ROUTE SOCBYPASS VARCHAR(3) Indicates if the normal routing mechanism is being bypassed.

Nullable NO The normal routing mechanism is being used.

YES The normal routing mechanism is being bypassed.

Contains null if value is not specified or if socket is not an address


family of AF_INET or AF_INET6.

SOCKET_DEBUG SOCDEBUG VARCHAR(3) Indicates if low-level debugging is active.

Nullable NO Low-level debugging is not active.

YES Low-level debugging is active.

Contains null if value is not specified.

SOCKET_ERROR SOCERROR INTEGER Indicates if there any pending errors in the socket. A value of zero
indicates no pending errors. Otherwise, the value indicates the
Nullable error number.
Contains null if value is not specified.

SOCKET_KEEP_ALIVE SOCALIVE VARCHAR(3) Indicates if the connection is being kept up by periodic


transmissions.
Nullable
NO The connection is not being kept up by periodic
transmissions.

YES The connection is being kept up by periodic


transmissions.

Contains null if value is not specified or if socket is not an address


family of AF_INET or AF_INET6 and type SOCK_STREAM.

SOCKET_LINGER SOCLINGER VARCHAR(3) Indicates whether the system attempts to deliver any buffered
data or if the system discards it when a close() is issued.
Nullable
NO The system attempts to send buffered data with an
infinite wait time.

YES The system attempts to send buffered data for


SOCKET_LINGER_TIME seconds. If the data is not
deliverable within that period of time, it is discarded.

Contains null if value is not specified.

SOCKET_LINGER_TIME SOCLTIME BIGINT The time, in seconds, the system will wait to send buffered data.

Nullable Contains null if value is not specified or if SOCKET_LINGER is NO.

SOCKET_OUT_OF_BAND_DATA SOCOUTBAND VARCHAR(3) Indicates if out-of-band data is received inline with normal data.

Nullable NO Out-of-band data is not received inline with normal data.

YES Out-of-band data is received inline with normal data.

Contains null if value is not specified or if socket is not an address


family of AF_INET or AF_INET6.

SOCKET_RECEIVE_BUFFER_SIZE SOCRCVBUF BIGINT The size of the receive buffer.

Nullable Contains null if value is not specified.

SOCKET_RECEIVE_LOW_WATER_ SOCRCVSZ BIGINT The size of the receive low-water mark. The default size is 1.
MARK_SIZE Nullable Contains null if value is not specified or if socket is not type
SOCK_STREAM.

560 IBM i: Performance and Query Optimization


Table 122. NETSTAT_INFO view (continued)

Column Name System Column Name Data Type Description

SOCKET_REUSE_ADDRESS SOCREUSE VARCHAR(3) Indicates if the local socket address can be reused.

Nullable NO The local socket address cannot be reused.

YES The local socket address can be reused.

Contains null if value is not specified or if socket is not an


address family of AF_INET or AF_INET6 and type SOCK_STREAM
or SOCK_DGRAM.

SOCKET_SEND_BUFFER_SIZE SOCSENDBUF BIGINT The size of the send buffer.

Nullable Contains null if value is not specified.

SOCKET_TYPE SOCTYPE VARCHAR(14) The socket type. Values are:

Nullable SOCK_DGRAM Datagram type.

SOCK_RAW Raw type.

SOCK_SEQPACKET Sequential packet type.

SOCK_STREAM Stream type.

Contains null if value is not specified.

SOCKET_LOOPBACK SOCLOOPBK VARCHAR(3) Indicates if the loopback feature is being used.

Nullable NO The loopback feature is not being used.

YES The loopback feature is being used.

Contains null if value is not specified.

SOCKET_RECEIVE_TIMEOUT SOCRCVTO BIGINT The receive timeout value.

Nullable Contains null if value is not specified.

SOCKET_SEND_LOW_WATER_ SOCSENDSZ BIGINT The size of the send low-water mark.


MARK_SIZE Nullable Contains null if value is not specified.

SOCKET_SEND_TIMEOUT SOCSENDTO BIGINT The send timeout value.

Nullable Contains null if value is not specified.

Example
Return information about all network connections for user QLWISVR.

SELECT * FROM QSYS2.NETSTAT_INFO


WHERE BIND_USER = 'QLWISVR'

Related information
Internet Protocol version 6

NETSTAT_INTERFACE_INFO view
The NETSTAT_INTERFACE_INFO view returns information about IPv4 and IPv6 interfaces.
The values returned for the columns in the view are closely related to the values returned by List Network
Interfaces API. Refer to the API for more detailed information.
Authorization: None required.
The following table describes the columns in the view. The system name is NS_INTER. The schema is
QSYS2.

Database performance and query optimization 561


Table 123. NETSTAT_INTERFACE_INFO view

Column Name System Column Name Data Type Description

CONNECTION_TYPE CONN_TYPE CHAR(4) The type of connection.

IPV4 The connection is an IPv4 connection.

IPV6 The connection is an IPv6 connection.

INTERNET_ADDRESS INT_ADDR VARCHAR(45) The internet address of the interface.


For IPv4:
• The address is in IPv4 address format.
Can contain the special value:

*IP4DHCP The interface has been configured to use DHCP


to obtain an IPv4 address.

For IPv6:
• The address is in IPv6 address format.
Can contain the special value:

*IP6SAC This interface will use Stateless Address Auto-


configuration to obtain an IPv6 address.

NETWORK_ADDRESS NET_ADDR VARCHAR(45) The internet address of the IP network or subnetwork to which the
interface is attached.
For IPv4:
• The address is in IPv4 address format.
For IPv6:
• The address is in IPv6 address format.

SUBNET_MASK SUBNET_MSK VARCHAR(15) The subnet mask for the network, subnet, and host address
fields of the internet address that defines the subnetwork for an
Nullable interface.
Contains null if this is an IPv6 connection.

PREFIX_LENGTH PRE_LEN INTEGER The prefix length defines how many bits of the IPv6 internet
address are in the prefix. It specifies how many of the left-most
Nullable bits of the address make up the prefix. The prefix length is used to
generate network and host addresses.
Contains null if this is an IPv4 connection.

LINE_DESCRIPTION LINE_DES VARCHAR(10) The name of the communications line description that identifies
the physical network associated with an interface. Can contain the
following special values:

*LOOPBACK This is the loopback interface. Processing


associated with a loopback interface does not
extend to a physical line.

*VIRTUALIP The virtual interface is a circuitless interface.

For IPv4, the following additional values can be returned.

*IPS The interface is used by Internet Protocol (IP) over SNA.

*OPC The interface is attached to the optical bus


(OptiConnect).

562 IBM i: Performance and Query Optimization


Table 123. NETSTAT_INTERFACE_INFO view (continued)

Column Name System Column Name Data Type Description

INTERFACE_LINE_TYPE LINE_TYPE VARCHAR(6) The type of line used by the interface. Only supported line types
are listed here; obsolete values could be returned for inactive
configurations.

ASYNC Asynchronous communications protocol.

ELAN Ethernet local area network protocol.

L2TP Layer Two Tunneling protocol.

PPP Point-to-Point protocol.

PPPOE Point-to-Point over Ethernet protocol.

VETH Virtual Ethernet protocol.

Can also contain one of the following special values:

ERROR A system error other than those for NOTFND was


received while trying to determine the link type for
an interface.

NONE Line is not defined. This value is used for the following
interfaces: *LOOPBACK, *VIRTUALIP, *OPC. There is
no line type value for this interface.

NOTFND Not found. The line description object for this


interface cannot be found.

INTERFACE_STATUS STATUS VARCHAR(12) The current status of the logical interface.

ACTIVE The interface has been started and is running.

DOD This interface is being used for Point-to-Point


(PPP) Dial-on-Demand.

ENDING The operating system is processing the request


to end this interface.

FAILED The line description associated with this


interface has entered the failed state.

FAILED (TCP) An error was detected in the IBM TCP/IP


Licensed Internal Code.

INACTIVE The interface has not been started.

RCYCNL A hardware failure has occurred and the line


description associated with this interface is in
the recovery canceled (RCYCNL) state.

RCYPND An error with the physical line associated with


this interface was detected by the system. The
line description associated with this interface is
in the recovery pending (RCYPND) state.

STARTING The operating system is processing the request


to start this interface.

For IPv4, the following additional value can be returned.

ACQUIRING The operating system is attempting to obtain an


IP address from a Dynamic Host Configuration
Protocol (DHCP) server.

For IPv6, the following additional value can be returned.

DEPRECATED The interface address preferred lifetime has


expired but the valid lifetime has not yet expired.

Database performance and query optimization 563


Table 123. NETSTAT_INTERFACE_INFO view (continued)

Column Name System Column Name Data Type Description

INTERFACE_SOURCE SOURCE VARCHAR(9) Specifies how this interface was added to the protocol stack.

Nullable LOOPBACK The interface was added by the protocol stack as


the loopback address.

STATELESS The interface was added by IPv6 address


autoconfiguration.

STATEFUL The interface was added by Dynamic Host


Configuration Protocol version 6 (DHCPv6)
configuration.

MANUAL The interface was added by manual configuration.

Contains null if this is an IPv4 connection.

SERVICE_TYPE SRVC_TYPE VARCHAR(9) The type of service that defines how the internet hosts and routers
should make trade-offs between throughput, delay, reliability, and
Nullable cost.

MAXRLB A higher level of effort to ensure delivery is


important for datagrams with the maximize
reliability indication.

MAXTHRPUT High data rate is important for datagrams with


the maximize throughput indication.

MINCOST Lower cost is important for datagrams with the


minimize monetary cost indication.

MINDELAY Prompt delivery is important for datagrams with


the minimize delay indication.

NORMAL Normal service is used for delivery of datagrams.

OTHER An Internet Protocol (IP) over SNA interface.

Contains null if this is an IPv6 connection.

VIRTUAL_LAN_ID LAN_ID VARCHAR(4) The virtual LAN to which this interface belongs according to IEEE
standard 802.1Q. Can also contain the following special value:

NONE The interface does not belong to a virtual LAN.

MAXIMUM_TRANSMISSION_ MTU VARCHAR(10) The maximum transmission unit (MTU) value specified for this
UNIT interface. Either an integer value or this special value:

LIND The interface is not currently active and the MTU was
specified as *LIND.

For IPv4, the following additional value can be returned.

OTHER An Internet Protocol (IP) over SNA interface.

CONFIGURED_MAXIMUM_ CFG_MTU VARCHAR(10) The configured maximum transmission unit value specified for this
TRANSMISSION_UNIT interface. Either an integer value or this special value:

LIND The interface is not currently active and the MTU was
specified as *LIND.

AUTOSTART AUTOSTART VARCHAR(3) Specifies whether the interface is automatically started when the
protocol stack is activated.

NO This interface is not automatically started.

YES This interface is automatically started.

DAD_MAX_TRANSMITS DAD_MAX BIGINT The maximum number of duplicate address detection (DAD)
transmissions the protocol stack will send out on this interface.
Nullable
Contains null if this is an IPv4 connection.

564 IBM i: Performance and Query Optimization


Table 123. NETSTAT_INTERFACE_INFO view (continued)

Column Name System Column Name Data Type Description

HOST_ADDRESS HOST_ADDR VARCHAR(45) Host portion of the internet address.


For IPv4:
• Host portion of the Internet address, in dotted decimal notation,
as determined by the subnet mask specified for this interface.
For IPv6:
• Host portion of the Internet address, in IPv6 address format, as
determined by the prefix length configured for this interface.

DIRECTED_BROADCAST_ DIRBRDADR VARCHAR(15) The Internet address, in dotted decimal notation, used to
ADDRESS broadcast to all systems attached to the same network or
Nullable subnetwork as this interface.
Contains null if this is an IPv6 connection or if interface is attached
to a network that does not support a broadcast operation.

ASSOCIATED_LOCAL_ ASCLCLINT VARCHAR(15) The Internet address, in dotted decimal notation, of the local
INTERFACE interface that has been associated with this interface.
Nullable
Contains null if this is an IPv6 connection or if no association has
been made between this interface and another local interface.

CHANGE_STATUS CHGSTS VARCHAR(6) The status of the most recent change to this interface in the
dynamic tables used by the TCP/IP protocol stack.
Nullable
ADD Add interface request processed.

CHANGE Change interface request processed.

END End interface request processed.

START Start interface request processed.

Contains null if this is an IPv6 connection.

PACKET_RULES PKT_RULES VARCHAR(17) The kind of packet rules data available for this line.

Nullable NONE No filters and no NAT are loaded for this


line.

NAT NAT is enabled for this line.

FILTERS Filters are defined for this line.

NAT_FILTERS NAT enabled and filters defined for this


line.

FILTERS_IPSEC Filters and IPSec filters are defined for


this line.

NAT_FILTERS_IPSEC NAT enabled and Filters and IPsec filters


defined for this line.

Contains null if packet rules data is unknown.

INTERFACE_TYPE TYPE VARCHAR(12) The interface type:

Nullable BROADCAST Broadcast capable.

NONBROADCAST Non-broadcast capable.

UNNUMBERED Unnumbered network.

Contains null if this is an IPv6 connection.

NETWORK_FULL_NAME NET_FNAME VARCHAR(24) The complete name of the network that this interface is a part of.

Nullable Contains null if this is an IPv6 connection or if there is no network


name.

INTERFACE_FULL_NAME FNAME VARCHAR(24) The complete interface name.

Nullable Contains null if this is an IPv6 connection or if there is no interface


name.

ALIAS_NAME ALIAS_NAME VARGRAPHIC(50) Name given to the interface to use as an alternate to the IP
CCSID 1200 address.

Nullable Contains null if there is no alias name.

Database performance and query optimization 565


Table 123. NETSTAT_INTERFACE_INFO view (continued)

Column Name System Column Name Data Type Description

INTERFACE_TEXT LABEL VARGRAPHIC(50) Description of the interface.


CCSID 1200
Contains null if there is no interface description.
Nullable

DHCP_CREATED DHCPCRT VARCHAR(3) Specifies whether this interface was created using Dynamic Host
Configuration Protocol (DHCP).
Nullable
NO This interface was not created using DHCP.

YES This interface was created using DHCP.

Contains null if this is an IPv6 connection.

DHCP_DYNAMIC_DNS_ DHCPDYNDNS VARCHAR(3) Specifies whether dynamic updates to Domain Name System
UPDATES (DNS) tables are enabled or not.
Nullable
NO DNS updates are disabled.

YES DNS updates are enabled.

Contains null if this is an IPv6 connection or if interface was not


created by DHCP.

DHCP_LEASE_EXPIRATION DHCPLEXP TIMESTAMP(0) The timestamp when the DHCP lease will expire.

Nullable Contains null if this is an IPv6 connection or if interface was not


created by DHCP.

DHCP_LEASE_OBTAINED DHCPLOBT TIMESTAMP(0) The timestamp when the DHCP lease was obtained or renewed.

Nullable Contains null if interface was not created by DHCP.

DHCP_USE_UNIQUE_ID DHCPUSEUID VARCHAR(3) Whether the DHCP unique identifier (DUID) is used as the client
identification for the Dynamic Host Configuration Protocol (DHCP).
Nullable
NO The hardware (MAC) address is used for the client ID.

YES The DHCP unique identifier is used for the client ID or this
is an IPv6 connection.

Contains null if interface was not created by DHCP.

DHCP_SERVER_UNIQUE_ID DHCPSRVUID VARCHAR(30) Specifies the DHCP unique identifier (DUID) of the DHCP server
from which the IP address was obtained.
Nullable
Contains null if this is an IPv4 connection or if interface was not
created by DHCP.

DHCP_SERVER_ADDRESS DHCPSRVADD VARCHAR(15) The Internet address, in dotted decimal notation, of the DHCP
server from which the DHCP lease was obtained or renewed.
Nullable
Contains null if this is an IPv6 connection or if interface was not
created by DHCP.

PREFERRED_INTERFACE_ PREFDFTRTE VARCHAR(3) This field describes whether the preferred proxy interfaces are
DEFAULT_ROUTE based on the system's default route.
Nullable
NO The default route is not used to determine the preferred
interface.

YES The default route is used to determine the preferred


interface.

Contains null if this is an IPv6 connection.

PREFERRED_INTERFACE_LIST PREFIFCLST VARCHAR(159) A list of up to 10 preferred interface internet addresses. Each


internet address within the preferred interface list is given in
Nullable dotted decimal notation. When there is more than one internet
address, a single blank separates the addresses.
Contains null if this is an IPv6 connection or if a preferred interface
list is not being used.

PREFERRED_PHYSICAL_LINE_ PREFLINLST VARCHAR(159) A list of up to 10 preferred physical line list entries. Each entry in
LIST the list is formatted as LINE_DESCRIPTION:VIRTUAL_LAN_ID.
Nullable The line description can be up to 10 characters long. The virtual
LAN ID can be up to 4 characters long. When there is more than
one preferred physical line, a single blank separates entries.
Contains null if this is an IPv4 connection.

566 IBM i: Performance and Query Optimization


Table 123. NETSTAT_INTERFACE_INFO view (continued)

Column Name System Column Name Data Type Description

ADDRESS_TYPE ADDR_TYPE VARCHAR(9) The type of IPv6 address that is assigned to this network interface.

Nullable ANYCAST An identifier for a set of interfaces (typically


belonging to different nodes). A packet sent to
an anycast address is delivered to one of the
interfaces identified by that address (the "nearest"
one, according to the routing protocols' measure of
distance).

MULTICAST An identifier for a set of interfaces (typically


belonging to different nodes). A packet sent to
a multicast address is delivered to all interfaces
identified by that address.

UNICAST An identifier for a single interface. A packet sent


to a unicast address is delivered to the interface
identified by that address.

Contains null if this is an IPv4 connection.

ADDRESS_CLASS ADDR_CLASS VARCHAR(9) The class of IPv6 address that is assigned to this network
interface.
Nullable
PUBLIC The interface is a public one.

TEMPORARY The interface is a temporary one used for privacy


extensions.

Contains null if this is an IPv4 connection.

ADDRESS_PREFERRED_LIFETIME ADDPLIFE BIGINT The length of time that a "valid" address is preferred, in seconds. A
negative value indicates that the address preferred lifetime expired
Nullable that number of seconds ago.
Contains null if this is an IPv4 connection or if this address has an
infinite preferred lifetime.

ADDRESS_VALID_LIFETIME ADDVLIFE BIGINT The length of time, in seconds, that an address remains in a "valid"
state. A negative value indicates that the address valid lifetime
Nullable expired that number of seconds ago.
Contains null if this is an IPv4 connection or if this address has an
infinite valid lifetime.

ADDRESS_PREFERRED_ ADDPFRLE TIMESTAMP(0) The timestamp when this address will no longer be in the preferred
LIFETIME_EXPIRATION state. If the timestamp is in the future, the address is still
Nullable preferred. If the timestamp is in the past, then this address is no
longer preferred.
Contains null if this is an IPv4 connection or if this address has an
infinite preferred lifetime which never expires.

ADDRESS_VALID_LIFETIME_ ADDVLDLE TIMESTAMP(0) The timestamp when this address will expire or did expire. If the
EXPIRATION timestamp is in the future, the address has not expired yet. If the
Nullable timestamp is in the past, then this address has expired and is
still being returned for a short period of time to indicate that the
interface ceased to function because its valid lifetime expired.
Contains null if this is an IPv4 connection or if this address has an
infinite valid lifetime which never expires.

ON_LINK ON_LINK VARCHAR(3) Whether or not this interface and all IPv6 addresses with the same
prefix are on the same link.
Nullable
NO Addresses with the same prefix are not assumed to be on
the same link.

YES Addresses with the same prefix are assumed to be on the


same link and directly reachable.

Contains null if this is an IPv4 connection or if


INTERNET_ADDRESS is *IP6SAC

PROXY_ARP_ENABLED PRXARPENB VARCHAR(3) Indicates whether Proxy ARP is currently active for this interface.

Nullable NO Proxy ARP not enabled.

YES Proxy ARP enabled.

Contains null if this is an IPv6 connection.

Database performance and query optimization 567


Table 123. NETSTAT_INTERFACE_INFO view (continued)

Column Name System Column Name Data Type Description

PROXY_ARP_ALLOWED PRXARPALW VARCHAR(3) Indicates whether Proxy ARP has been configured to be allowed or
not allowed.
Nullable
NO Proxy ARP not allowed.

YES Proxy ARP allowed.

Contains null if this is an IPv6 connection or if interface is not


Opticonnect (*OPC) or Virtual Ethernet.

CURRENT_PROXY_AGENT_LINE PRXAGT VARCHAR(10) Name of the communication line description that is used with
the IPv6 interface for virtual IP address (VIPA) proxy Neighbor
Nullable Discovery.
Contains null if this is an IPv4 connection or if no association has
been made between this interface and another physical interface.

CURRENT_PROXY_AGENT_ PRXAGTLAN VARCHAR(4) The virtual LAN to which the proxy agent line belongs according
LINE_VIRTUAL_LAN_ID to IEEE standard 802.1Q. Can also contain the following special
Nullable value:

NONE There is no virtual LAN identifier associated with the


current proxy agent line.

Contains null if this is an IPv4 connection or if no association has


been made between this interface and another physical interface.

LAST_CHANGE_TIMESTAMP LASTCHG TIMESTAMP(0) The timestamp of the most recent change to this interface in the
dynamic tables used by the protocol stack.
Nullable
Contains null if the interface has never been changed.

Example
Return information about all interfaces which are using Virtual Ethernet protocol..

SELECT * FROM QSYS2.NETSTAT_INTERFACE_INFO


WHERE INTERFACE_LINE_TYPE = 'VETH'

Related information
Internet Protocol version 6

NETSTAT_JOB_INFO view
The NETSTAT_JOB_INFO view returns information about jobs using IPv4 and IPv6 network connections.
The values returned for the columns in the view are closely related to the values returned by the Retrieve
Network Connection Data (QtocRtvNetCnnDta) API.
Authorization: None required.
The following table describes the columns in the view. The system name is NS_JOB. The schema is
QSYS2.
Table 124. NETSTAT_JOB_INFO view

Column Name System Column Name Data Type Description

CONNECTION_TYPE CONN_TYPE CHAR(4) The type of connection.

IPV4 The connection is an IPv4 connection.

IPV6 The connection is an IPv6 connection.

568 IBM i: Performance and Query Optimization


Table 124. NETSTAT_JOB_INFO view (continued)

Column Name System Column Name Data Type Description

REMOTE_ADDRESS RMT_ADDR VARCHAR(45) The internet address of the remote host.


For IPv4:
• The address is in IPv4 address format. A value of 0.0.0.0
indicates that either the system is waiting for a connection to
open or that a UDP socket is being used. A value of 0 means
that the connection is a listening or UDP socket so this field
does not apply.
For IPv6:
• The address is in IPv6 address format. A value of :: means
that the connection is a listening socket so this field does not
apply.

REMOTE_PORT RMT_PORT INTEGER The remote host port number. A value of 0 means that the
connection is a listening or UDP socket, so this field does not
apply.

REMOTE_PORT_NAME RMT_NAME VARGRAPHIC(14) The remote host well-known port name or the name from the
CCSID 1200 service table entry.

Nullable Contains null if there is no well-known port name.

LOCAL_ADDRESS LOCAL_ADDR VARCHAR(45) The local address of this connection on this system.
For IPv4:
• The address is in IPv4 address format. A value of 0.0.0.0
indicates that either the system is waiting for a connection to
open or that a UDP socket is being used.
For IPv6:
• The address is in IPv6 address format. A value of :: means the
local application specified that any local internet address can
be used.

LOCAL_PORT LOCAL_PORT INTEGER The local system port number.

LOCAL_PORT_NAME LOCAL_NAME VARGRAPHIC(14) The local system well-known port name or the name from the
CCSID 1200 service table entry.

Nullable Contains null if there is no well-known port name.

AUTHORIZATION_NAME USER_NAME VARCHAR(10) The effective user profile of the thread for which information is
being retrieved. This name may differ from the user portion of
Nullable the job name.
Contains null when SLIC_TASK_NAME is not null or if JOB_NAME
is the special value *SIGNON.

JOB_NAME JOB_NAME VARCHAR(28) The qualified job name. Can also contain the following special
value:
Nullable
*SIGNON This connection is a telnet connection and the
system is performing sign-on processing or is
displaying a sign-on prompt on it.

Contains null when SLIC_TASK_NAME is not null.

JOB_NAME_SHORT JOB_NAME_S VARCHAR(10) The name of the job.

Nullable Contains the null value when JOB_NAME is *SIGNON or


SLIC_TASK_NAME is not null.

JOB_USER JOB_USER VARCHAR(10) The user profile that started the job.

Nullable Contains the null value when JOB_NAME is *SIGNON or


SLIC_TASK_NAME is not null.

JOB_NUMBER JOB_NUMBER VARCHAR(6) The job number of the job.

Nullable Contains the null value when JOB_NAME is *SIGNON or


SLIC_TASK_NAME is not null.

SLIC_TASK_NAME SLIC_TASK VARCHAR(16) The task name as identified to the system.

Nullable Contains null when JOB_NAME is not null.

Database performance and query optimization 569


Table 124. NETSTAT_JOB_INFO view (continued)

Column Name System Column Name Data Type Description

INTERNAL_JOB_ID JOB_ID BINARY(16) A value that can be used by system APIs to speed the process of
locating the job on the system.
Nullable
Contains null if JOB_NAME is the special value *SIGNON or if
SLIC_TASK_NAME is not null.

JOB_TYPE JOB_TYPE VARCHAR(11) The type of job:

Nullable AUTOSTART The job is an autostart job.

BATCH The job is a batch job.

INTERACTIVE The job is an interactive job.

MONITOR The job is a subsystem monitor job.

READER The job is a spooled reader job.

SCPF The job is the SCPF system job.

SYSTEM The job is a system job.

WRITER The job is a spooled writer job.

Contains null if JOB_NAME is the special value *SIGNON or if


SLIC_TASK_NAME is not null.

Example
Return information about all jobs using IPv4 network connections.

SELECT * FROM QSYS2.NETSTAT_JOB_INFO


WHERE CONNECTION_TYPE = 'IPV4'

Related information
Internet Protocol version 6

NETSTAT_ROUTE_INFO view
The NETSTAT_ROUTE_INFO view returns information about IPv4 and IPv6 routes.
The values returned for the columns in the view are closely related to the values returned by List Network
Routes API. Refer to the API for more detailed information.
Authorization: None required.
The following table describes the columns in the view. The system name is NS_ROUTE. The schema is
QSYS2.
Table 125. NETSTAT_ROUTE_INFO view

Column Name System Column Name Data Type Description

CONNECTION_TYPE CONN_TYPE CHAR(4) The type of connection.

IPV4 The connection is an IPv4 connection.

IPV6 The connection is an IPv6 connection.

ROUTE_DESTINATION ROUTE_DEST VARCHAR(45) The Internet Protocol address of the ultimate destination reached
by this route.
For IPv4:
• The address is in IPv4 address format. When used in
combination with the subnet mask and the type of service
values, the route destination identifies a route to a network or
system. A value of 0.0.0.0 means that the route destination is
the default route.
For IPv6:
• The address is in IPv6 address format. When used in
combination with the prefix length, the route destination
identifies a route to a network or host.

570 IBM i: Performance and Query Optimization


Table 125. NETSTAT_ROUTE_INFO view (continued)

Column Name System Column Name Data Type Description

SUBNET_MASK SUBNET_MSK VARCHAR(15) The actual value of the subnet mask for the route destination in
dotted-decimal notation. A value of 0.0.0.0 means no value is
Nullable defined.
Contains null if this is an IPv6 connection.

NEXT_HOP NEXT_HOP VARCHAR(45) The internet address of the first system on the path from your
system to the route destination.
For IPv4:
• The address is in IPv4 address format.
For IPv6:
• The address is in IPv6 address format.
Can contain the following special value:

*DIRECT This is the next hop value of a route that is


automatically created.

PREFIX_LENGTH PRE_LEN INTEGER The prefix length defines how many bits of the route destination
IPv6 address are in the prefix. It specifies how many of the left-
Nullable most bits of the address make up the prefix. The prefix length is
used to generate network and host addresses.
Contains null if this is an IPv4 connection.

ROUTE_STATUS ROUTE_STS VARCHAR(10) The current state of the route.

Nullable DOD This route is used for Point-to-Point (PPP) Dial-on-


Demand. Currently, this Dial-on-Demand route is not
available. The route will become available when a Dial-
on-Demand session is initiated for the interface this
route is associated with.

For IPv4:

YES The router specified by the next hop value for


this interface is available for use.

NO The router specified by the next hop value for


this interface is not available for use.

NO GATEWAY The router specified by the next hop value for


this interface is not available for use, the router
may be experiencing a problem.

For IPv6:

ACTIVE This route is currently active and is in the current


route search path.

INACTIVE This route is not in the route search path and is not
being used.

Contains null if the state is unknown.

ROUTE_MAXIMUM_ ROUTE_MTU VARCHAR(10) The maximum transmission unit (MTU) value for this route in
TRANSMISSION_UNIT bytes. Can be either a number or one of the following special
values:
For IPv4:

IFC The route is not currently active and the MTU was
specified as *IFC.

OTHER An Internet Protocol (IP) over SNA interface.

For IPv6:

*IP6LINMTU This route uses the MTU of the line it is bound


to.

Database performance and query optimization 571


Table 125. NETSTAT_ROUTE_INFO view (continued)

Column Name System Column Name Data Type Description

CONFIGURED_ROUTE_ CFG_RT_MTU VARCHAR(10) A number representing the configured maximum transmission


MAXIMUM_ unit (MTU) value for this route, in bytes. Can be either a number
Nullable or the following special value:
TRANSMISSION_UNIT
*IP6LINMTU The route MTU was specified as *IP6LINMTU,
the MTU value of the line to which this route is
bound.

Contains null if this is an IPv4 connection.

ROUTE_TYPE ROUTE_TYPE VARCHAR(8) The type of route.

Nullable DFTROUTE A default route.

DIRECT A route to a network or subnetwork to which this


system has a direct physical connection.

HOST A route to a specific remote host.

NET An indirect route to a remote network.

SUBNET An indirect route to a remote subnetwork. This


option is only for IPv4 connections.

Contains null if the type of route is unknown.

572 IBM i: Performance and Query Optimization


Table 125. NETSTAT_ROUTE_INFO view (continued)

Column Name System Column Name Data Type Description

ROUTE_SOURCE ROUTE_SRC VARCHAR(18) Specifies how this route was added to the routing table.

Nullable For IPv4:

CFG The route was added using the configuration


commands of the local system.

ICMP The route was added with the Internet Control


Message Protocol (ICMP) redirect mechanism.

OTHER The route was added with a sockets input/output


control (IOCtl) or other mechanism.

RIP The route was added by the Routing Information


Protocol (RIP).

SNMP The route was added by the Simple Network


Management Protocol (SNMP).

For IPv6:

AUTOCONFIG This route was added because of


an interface added by stateless
autoconfiguration.

BGP This route was added by the Border


Gateway Protocol (BGP).

CFGIFC The route was added because of a


manually configured interface.

CFGRTE The route was manually configured.

IDRP This route was added by the Inter-


Domain Routing Protocol (IDRP).

IGRP This route was added by the Interior


Gateway Routing Protocol (IGRP).

OSPF The route was added by the Open


Shortest Path First (OSPF) protocol.

RA_PREFIX_INFO This route was added because of


the presence of a Prefix Information
Option on a Router Advertisement
packet received by the system.

RA_ROUTE_INFO This route was added because of


the presence of a Route Information
Option on a Router Advertisement
packet received by the system.

RA_ROUTER_LIFETIME This route was added because of


the presence of a non-zero value in
the Router Lifetime field in a Router
Advertisement packet received by
the system.

REDIRECT This route was added by the ICMPv6


redirect mechanism.

RIP The route was added by the Routing


Information Protocol (RIP).

ROUTING This route was determined to be


necessary and added by the TCP/IP
stack on this system.

SNMP This route was added by the Simple


Network Management Protocol
(SNMP).

Contains null if the route source is not known.

Database performance and query optimization 573


Table 125. NETSTAT_ROUTE_INFO view (continued)

Column Name System Column Name Data Type Description

SERVICE_TYPE SRVC_TYPE VARCHAR(9) The type of service that defines how the internet hosts and
routers should make trade-offs between throughput, delay,
Nullable reliability, and cost.

MAXRLB A higher level of effort to ensure delivery is


important for datagrams with the maximize
reliability indication.

MAXTHRPUT High data rate is important for datagrams with


the maximize throughput indication.

MINCOST Lower cost is important for datagrams with the


minimize monetary cost indication.

MINDELAY Prompt delivery is important for datagrams with


the minimize delay indication.

NORMAL Normal service is used for delivery of


datagrams.

OTHER An Internet Protocol (IP) over SNA interface.

Contains null if this is an IPv6 connection.

ROUTE_PROTOCOL ROUTE_PTCL VARCHAR(7) Specifies the protocol that was used to generate this route.

Nullable BGP Border Gateway protocol.

IDRP InterDomain Routing protocol.

IGRP InterGateway Routing protocol.

LOCAL Local configuration.

NDISC Neighbor discovery.

NETMGMT Network Management protocol.

OSPF Open Shortest Path First protocol.

OTHER None of the listed protocols.

RIP Routing Information protocol.

Contains null if this is an IPv4 connection.

ROUTE_PREFERENCE ROUTE_PREF VARCHAR(6) The preference of this route during route selection.

Nullable LOW This route has a low preference.

MEDIUM This route has a medium preference.

HIGH This route has a high preference.

Contains null if this is an IPv4 connection.

LOCAL_BINDING_TYPE LOCALTYPE VARCHAR(7) The type of line to which this route is bound.

Nullable • DYNAMIC
• STATIC
Contains null if this is an IPv6 connection.

LOCAL_BINDING_INTERFACE LOCALIFC VARCHAR(15) The IP interface to bind to this route.

Nullable Contains null if this is an IPv6 connection.

574 IBM i: Performance and Query Optimization


Table 125. NETSTAT_ROUTE_INFO view (continued)

Column Name System Column Name Data Type Description

LOCAL_BINDING_INTERFACE_ LOCALSTS VARCHAR(12) The current status of the logical interface.


STATUS Nullable ACTIVE The interface has been started and is running.

DOD This interface is being used for Point-to-Point


(PPP) Dial-on-Demand.

DUPLICATE Another host on the LAN responded to a packet


destined for this logical interface.

ENDING The operating system is processing the request


to end this interface.

FAILED The line description associated with this


interface has entered the failed state.

FAILED (TCP) An error was detected in the IBM TCP/IP


Licensed Internal Code.

INACTIVE The interface has not been started.

RCYCNL A hardware failure has occurred and the line


description associated with this interface is in
the recovery canceled (RCYCNL) state.

RCYPND An error with the physical line associated with


this interface was detected by the system. The
line description associated with this interface is
in the recovery pending (RCYPND) state.

STARTING The operating system is processing the request


to start this interface.

Contains null if this is an IPv6 connection.

LOCAL_BINDING_NETWORK_ LOCALADDR VARCHAR(15) The Internet address, in dotted decimal notation, of the IP
ADDRESS network or subnetwork that the interface is attached to.
Nullable
Contains null if this is an IPv6 connection.

LOCAL_BINDING_SUBNET_MASK LOCALMASK VARCHAR(15) The subnet mask for the network, subnet, and host address fields
for the local binding network address, in dotted decimal notation,
Nullable that defines the subnetwork for an interface.
Contains null if this is an IPv6 connection.

LOCAL_BINDING_LINE_ LOCALLINE VARCHAR(10) The name of the communications line description or virtual line
DESCRIPTION (L2TP) that identifies the network associated with an interface.
Can contain the following special values:

*LOOPBACK This is a loopback interface. Processing


associated with the loopback interface does not
extend to a physical line.

*OPC This interface is attached to the optical bus


(OptiConnect).

*VIRTUALIP The virtual interface is a circuitless interface.

LOCAL_BINDING_LINE_STATUS LOCALLSTS VARCHAR(8) The current operational status of the communications line to
which this route is bound.
Nullable
ACTIVE The line is operational.

FAILED The desired state of the line is Active, but it is


currently in the Inactive state.

INACTIVE The line is not operational.

Contains null if this is an IPv4 connection.

Database performance and query optimization 575


Table 125. NETSTAT_ROUTE_INFO view (continued)

Column Name System Column Name Data Type Description

LOCAL_BINDING_LINE_TYPE LOCALLTYPE VARCHAR(6) The type of line used by the interface. Only supported line types
are listed here; obsolete values could be returned for inactive
configurations.

ASYNC Asynchronous communications protocol.

ELAN Ethernet local area network protocol.

L2TP Layer Two Tunneling protocol.

PPP Point-to-Point protocol.

PPPOE Point-to-Point over Ethernet protocol.

VETH Virtual Ethernet protocol.

Can also contain one of the following special values:

ERROR A system error other than those for NOTFND was


received while trying to determine the link type for
an interface.

NONE Line is not defined. This value is used for


the following interfaces: *LOOPBACK, *VIRTUALIP,
*OPC. There is no line type value for this interface.

NOTFND Not found. The line description object for this


interface cannot be found.

LOCAL_BINDING_VIRTUAL_ LOCALLAN VARCHAR(4) The virtual LAN to which this route is bound. Can also contain the
LAN_ID following special value:

NONE No virtual LAN identifier is associated with the binding


line.

ROUTE_PRECEDENCE ROUTE_PRCD INTEGER Priority of route. Values are 1 to 10, with the lowest priority being
1.
Nullable
Contains null if this is an IPv6 connection.

ROUTE_TEXT LABEL VARGRAPHIC(50) Text description associated with the route.


CCSID(1200)
Contains null if there is no description.
Nullable

DUPLICATE DUPLICATE VARCHAR(6) Indicates whether this route is a duplicate of another route in the
routing table or not, and also whether there are any routes which
Nullable are duplicates of this route.

NO This route is not a duplicate of another route but it


does have duplicates.

UNIQUE This route is not a duplicate of another route and it


does not have any duplicates.

YES This route is a duplicate of another route.

Contains null if this is an IPv4 connection.

EXPIRATION EXPIRATION TIMESTAMP(0) The timestamp when this route will expire or did expire. If the
timestamp is in the future, the route has not expired yet. If the
Nullable timestamp is in the past, then this route has expired and is still
being returned for a short period of time to indicate that the route
ceased to function because its lifetime expired.
Contains null if this is an IPv4 connection or if the route will never
expire.

PPP_CONFIGURATION_PROFILE PPPCFGPRF VARCHAR(10) The name of the Point-to-Point Protocol (PPP) configuration
profile associated with this route.
Nullable
Contains null if this is an IPv4 connection or if Point-to-Point
Protocol is not being used with this route.

PPP_AUTHENTICATION_USER_ID PPPAUTUSR VARCHAR(24) The Point-to-Point Protocol authentication user id associated


with this route.
Nullable
Contains null if this is an IPv4 connection or if Point-to-Point
Protocol is not being used with this route.

576 IBM i: Performance and Query Optimization


Table 125. NETSTAT_ROUTE_INFO view (continued)

Column Name System Column Name Data Type Description

PPP_INTERNET_ADDRESS PPPINTADD VARCHAR(45) The internet address, in IPv6 address format, to which this Point-
to-Point route is bound.
Nullable
Contains null if this is an IPv4 connection or if Point-to-Point
Protocol is not being used with this route.

PPP_DIAL_ON_DEMAND_ PPPDODPRF VARCHAR(10) The name of the Dial-on-demand Remote Peer Enabled Point-to-
PROFILE Point profile associated with this route.
Nullable
Contains null if this is an IPv4 connection or if Point-to-Point
Protocol is not being used with this route.

LAST_CHANGE_TIMESTAMP LASTCHG TIMESTAMP(0) The timestamp of the most recent change to this route in the
dynamic tables used by the protocol stack.
Nullable
Contains null if the interface has never been changed.

Example
Return information about all routes which are available for use.

SELECT * FROM QSYS2.NETSTAT_ROUTE_INFO


WHERE ROUTE_STATUS = 'YES' OR ROUTE_STATUS = 'ACTIVE'

Related information
Internet Protocol version 6

NETWORK_ATTRIBUTE_INFO view
The NETWORK_ATTRIBUTE_INFO view returns a single row containing information about the network
attributes of the system.
The information returned is similar to the detail available through the Display Network Attributes
(DSPNETA) CL command, the Retrieve Network Attributes (RTVNETA) CL command, and the Retrieve
Network Attributes (QWCRNETA) API.
Authorization: None required.
The following table describes the columns in the view. The system name is NET_ATTR. The schema is
QSYS2.
Table 126. NETWORK_ATTRIBUTE_INFO view

Column Name System Column Name Data Type Description

HOST_NAME HOST_NAME VARCHAR(8) Name of the system where this information was
generated. This is the name set by CHGNETA.

PENDING_HOST_NAME PEND_HOST VARCHAR(8) The pending system name, if a change is pending.

Nullable Contains the null value if no change is pending.

NETWORK_ID NETWORK_ID VARCHAR(8) The local network ID assigned to the system.

CONTROL_POINT CTL_POINT VARCHAR(8) The local control point name for the system.

LOCATION LOCATION VARCHAR(8) The default local location name for the system.

MODE MODE VARCHAR(8) The default mode name for the system.

Nullable Contains the null value if there is no default mode.

Database performance and query optimization 577


Table 126. NETWORK_ATTRIBUTE_INFO view (continued)

Column Name System Column Name Data Type Description

APPN_NODE_TYPE NODETYPE VARCHAR(8) The advanced peer-to-peer networking (APPN) node


type.

*BEXNODE The node performs as a branch


extender node. The node performs as
an end node in the backbone APPN
network, and performs as a network
node server to end nodes within its
local domain.

*ENDNODE The node does not provide network


services to other nodes, but may
participate in the APPN network by
using the services of an attached
network server, or may operate in a
peer environment similar to migration
end nodes.

*NETNODE The node provides intermediate


routing, route selection services, and
distributed directory services for local
users and to end nodes and migration
end nodes that it is serving.

DATA_COMPRESSION DTACPR VARCHAR(10) Whether data compression is used when the system
is an SNA end node. This value is used by
mode descriptions that specify *NETATR for data
compression.
If data compression is requested by the remote
system, the data compression levels used by the
session are the lower of the requested levels and the
configured levels.

*ALLOW Data compression is allowed on


the session by the local system if
requested by a remote system. The
local system does not request that
compression be used.

*NONE Data compression is not allowed on


the session.

*REQUEST Data compression is requested on the


session by the local system. However,
the request can be refused or changed
to a lower compression level by the
remote system. Data compression is
allowed on the session if requested by
the remote system.

*REQUIRE Data compression is required on the


session. If the remote system does
not change the levels of compression
to the local system's exact requested
levels, the session is not established.
The data compression levels that the
local system requires are the specified
levels.

integer If either the receiving or sending


link has a line speed equal to or
less than this specified line speed,
this value indicates the need for
compression by requesting that the
remote systems compress the session
data. Otherwise, this value does not
indicate to the remote systems that
there is a need to compress the
data. Values range from 1 through
2147483647 bits per second.

578 IBM i: Performance and Query Optimization


Table 126. NETWORK_ATTRIBUTE_INFO view (continued)

Column Name System Column Name Data Type Description

INTERMEDIATE_DATA_ DTACPRINM VARCHAR(10) The level of data compression to request when the
COMPRESSION system is an SNA intermediate node.

*NONE Does not indicate to the remote


systems that there is a need to
compress the data.

*REQUEST Indicates the need for compression by


requesting that the remote systems
compress the session data.

integer If either the receiving or sending


link has a line speed equal to or
less than this specified line speed,
this value indicates the need for
compression by requesting that the
remote systems compress the session
data. Otherwise, this value does not
indicate to the remote systems that
there is a need to compress the
data. Values range from 1 through
2147483647 bits per second.

MAXIMUM_SESSIONS MAX_SSN INTEGER The maximum number of advanced program-


to-program communications (APPC) intermediate
Nullable sessions for an advanced peer-to-peer networking
(APPN) node type of *NETNODE or *BEXNODE.
Contains the null value when APPN_NODE_TYPE is
*ENDNODE.

ROUTE_ADDITION_RESISTANC RESISTANCE INTEGER The advanced peer-to-peer networking (APPN) route


E addition resistance for an APPN node type of
Nullable *NETNODE or *BEXNODE.
Contains the null value when APPN_NODE_TYPE is
*ENDNODE.

SERVER_NETWORK_ID_COUNT SRV_NETCNT INTEGER The number of network ID values in the


SERVER_NETWORK_IDS column.
Nullable
Contains the null value when APPN_NODE_TYPE is
not *ENDNODE.

SERVER_NETWORK_IDS SRV_NETIDS VARCHAR(248) CCSID 1208 The advanced peer-to-peer networking (APPN)
network node servers for an APPN node type of
Nullable *ENDNODE or *BEXNODE.
This list is returned as an array within a JSON object.
The array can contain up to five elements and is
identified by NET_IDS.
Each entry in the JSON array contains two JSON
objects:
• An object with a name of "NET_ID" and a value of a
network ID.
• An object with a name of "CTL_POINT" and a value
of the corresponding control point.
The special value of *LCLNETID for a network ID. This
indicates that the value of NETWORK_ID at the time
the node server is referred to is be used.
A special value of *ANY applies to the control
point. This indicates that the first network node that
offers services will become the network node server.
Any network node with the same network ID as
that specified for NETWORK_ID can be a potential
network node server.
Contains the null value when
SERVER_NETWORK_ID_COUNT is 0 or
APPN_NODE_TYPE is not *ENDNODE.

SERVER_NETWORK_ID SRV_NETID VARCHAR(9) The server network ID for the first entry in the
SERVER_NETWORK_IDS list. The special value of
Nullable *LCLNETID indicates that the value of NETWORK_ID
at the time the node server is referred to is be used.
Contains the null value when
SERVER_NETWORK_ID_COUNT is 0 or
APPN_NODE_TYPE is not *ENDNODE.

Database performance and query optimization 579


Table 126. NETWORK_ATTRIBUTE_INFO view (continued)

Column Name System Column Name Data Type Description

SERVER_CONTROL_POINT SRV_CTLPT VARCHAR(8) The server control point for the first entry in the
SERVER_NETWORK_IDS list. A special value of *ANY
Nullable indicates that the first network node that offers
services will become the network node server.
Any network node with the same network ID as
that specified for NETWORK_ID can be a potential
network node server.
Contains the null value when
SERVER_NETWORK_ID_COUNT is 0 or
APPN_NODE_TYPE is not *ENDNODE.

ALERT_STATUS ALERT_STS VARCHAR(9) Alert status controls the creation of local alerts.

*OFF Alerts are not created by the system.

*ON Alerts are created by a system for


all changeable conditions except
unattended conditions.

*UNATTEND Alerts are created by the system


for all alert conditions including
those which have the alert indicator
in the message description set to
*UNATTEND.

ALERT_LOGGING ALERT_LOG VARCHAR(6) Specifies which alerts are to be logged:

*ALL Both locally created alerts and incoming


alerts are logged.

*LOCAL Only locally created alerts are logged.

*NONE No alerts are logged.

*RCV Only alerts received from other nodes are


logged.

ALERT_PRIMARY_FOCAL_POIN ALERT_PRIM VARCHAR(4) Whether the system is an alert primary focal point.
T
*NO The system is not an alert primary focal
point.

*YES The system is defined to be an alert primary


focal point and provides focal point services
to all nodes in the network that are explicitly
defined in the sphere of control.

ALERT_DEFAULT_FOCAL_POIN ALERT_DFT VARCHAR(4) Whether the system is an alert default focal point.
T
*NO The system is not an alert default focal
point.

*YES The system is defined to be an alert default


focal point and provides focal point services
to all nodes in the network that are not
being serviced by another focal point.

ALERT_BACKUP_NETWORK_ID ALERT_BNET VARCHAR(8) The network ID of the system that provides backup
focal point services for alerts.
Nullable
These backup values define the system that provides
alert focal point services if the local system is
unavailable and ALERT_PRIMARY_FOCAL_POINT is
*YES. The backup focal point is only used by systems
in the primary sphere of control.
Contains the null value if no backup focal point is
defined.

ALERT_BACKUP_CONTROL_ ALERT_BCTL VARCHAR(8) The control point name of the system that provides
POINT backup focal point services for alerts.
Nullable
Contains the null value if no backup focal point is
defined.

580 IBM i: Performance and Query Optimization


Table 126. NETWORK_ATTRIBUTE_INFO view (continued)

Column Name System Column Name Data Type Description

ALERT_REQUEST_NETWORK_I ALERT_RQS VARCHAR(8) The network ID of the system that is requested to


D provide focal point services for alerts.
Nullable
The focal point to request values define the name of
the system that is requested to provide alert focal
point services.
Contains the null value if no backup focal point is
defined.

ALERT_REQUEST_CONTROL_ ALERT_RQSC VARCHAR(8) Specify the control point name of the system that is
POINT requested to provide focal point services for alerts.
Nullable
Contains the null value if no backup focal point is
defined.

ALERT_CONTROLLER ALERT_CTL VARCHAR(10) The name of the controller to be used for alerts in
a system service control point - physical unit (SSCP-
Nullable PU) session. This controller is ignored if the system
has a focal point (in which case the node is in another
system's sphere of control).
Contains the null value if no alert controller is
defined.

ALERT_HOLD_COUNT ALERT_HOLD INTEGER The maximum number of alerts to be created before


the alerts are sent over the system service control
Nullable point - physical unit session. Alerts are held by the
system until this number of alerts have been created.
If the alert controller (ALERT_CONTROLLER) network
attribute is being used to send alerts (SSCP-PU
session), alerts will be sent automatically regardless
of the ALERT_HOLD_COUNT network attribute when a
switched connection is made for other reasons.
Can contain the following special value:

-2 Indicates *NOMAX. The alerts are held


indefinitely. The alerts can be sent at a later
time by changing the ALRHLDCNT value on the
CHGNETA CL command to a lower value.

Contains the null value if no alert hold count is set.

ALERT_FILTER_LIBRARY ALERT_FTRL VARCHAR(10) The name of the library that contains the filter object.

Nullable Contains the null value if no alert filter is being used.

ALERT_FILTER ALERT_FTR VARCHAR(10) The name of the filter object that is used by the alert
manager when processing alerts.
Nullable
Contains the null value if no alert filter is being used.

MESSAGE_QUEUE_LIBRARY MSGQ_LIB VARCHAR(10) The library where MESSAGE_QUEUE resides.

MESSAGE_QUEUE MSGQ VARCHAR(10) The name of the message queue to which messages
received through the SNA distribution services
(SNADS) network are sent for:
• Users who have no message queue specified in
their user profile
• Users whose message queue is not available

OUTPUT_QUEUE_LIBRARY OUTQ_LIB VARCHAR(10) The library where OUTPUT_QUEUE resides.

OUTPUT_QUEUE OUTQ VARCHAR(10) The name of the output queue to which spooled
files received through the SNA distribution services
(SNADS) network are sent for users whose output
queue is not available.

Database performance and query optimization 581


Table 126. NETWORK_ATTRIBUTE_INFO view (continued)

Column Name System Column Name Data Type Description

JOB_ACTION JOB_ACTION VARCHAR(7) The action that is taken for any input stream received
through the SNA distribution services (SNADS)
network by the system.

*FILE The input stream is filed in the queue


of network files received for the user to
whom it was sent. That user may then
look at the input stream, end it, receive
it, or submit it to a job queue.

*REJECT The input stream is rejected by the


system. This action allows users to
secure their system from input streams
received through the network.

*SEARCH The table of network job entries is


searched to determine the action to be
taken for the input stream.

MAXIMUM_HOPS MAX_HOPS INTEGER The maximum number of times in an SNA distribution


services (SNADS) network that a distribution queue
entry originating at this node may be received and
routed on the path to its final destination. If this
number is exceeded, the distribution queue entry is
ended. When the distribution queue entry is ended, a
feedback status is sent back to the sender if it was
requested.

DDM_REQUEST_ACCESS DDM_RQS VARCHAR(8) How the system processes distributed data


management (DDM) and Distributed Relational
Database Architecture (DRDA) requests from other
systems.

*OBJAUT All requests are allowed and


controlled by the object authorization
on the system.

*REJECT The system does not allow DDM or


DRDA requests from remote systems.
This system can still use DDM or
DRDA, however, to access files or
SQL tables on remote systems.

*PROGRAM The program identified in


the DDM_REQUEST_LIBRARY and
DDM_REQUEST_PROGRAM columns
is used.

DDM_REQUEST_LIBRARY DDM_LIB VARCHAR(10) The name of the library that contains


DDM_REQUEST_PROGRAM.
Nullable
Contains the null value if DDM_REQUEST_ACCESS is
not *PROGRAM.

DDM_REQUEST_PROGRAM DDM_PGM VARCHAR(10) The name of a user-written validation program that


is called each time a DDM request is made from
Nullable a remote system. This program indicates to DDM
whether the request should proceed or be ended.
System security still applies.
Contains the null value if DDM_REQUEST_ACCESS is
not *PROGRAM.

582 IBM i: Performance and Query Optimization


Table 126. NETWORK_ATTRIBUTE_INFO view (continued)

Column Name System Column Name Data Type Description

CLIENT_REQUEST_ACCESS CLIENT_RQS VARCHAR(8) The way in which the system processes client
requests from other systems.

*OBJAUT Normal object authorizations are


checked for the client requests. For
example, authorization to retrieve
data from a database file for a
transfer function request is checked.

*REGFAC The registration facility is used to


determine whether to call an exit
program. If no exit program is
defined for an exit point and this
value is specified, *OBJAUT is used.

*REJECT The system rejects every request


from clients.

*PROGRAM The program identified in


the CLIENT_REQUEST_LIBRARY
and CLIENT_REQUEST_PROGRAM
columns is used.

CLIENT_REQUEST_LIBRARY CLIENT_LIB VARCHAR(10) The name of the library that contains


CLIENT_REQUEST_PROGRAM.
Nullable
Contains the null value if CLIENT_REQUEST_ACCESS
is not *PROGRAM.

CLIENT_REQUEST_PROGRAM CLIENT_PGM VARCHAR(10) The name of a user-written validation program that


is called each time a server request comes from a
Nullable client. The program is passed two parameters: the
first is used by the program to indicate to the server
application whether this client request should be
handled; the second describes the client request (the
name of the application and type request).
Contains the null value if CLIENT_REQUEST_ACCESS
is not *PROGRAM.

NETWORK_SERVER_DOMAIN NWS_DOMAIN VARCHAR(8) The LAN server domain associated with the file
server.

ALLOW_VIRTUAL_APPN VIRT_APPN VARCHAR(4) Specifies whether APPC sessions and devices are
allowed to use virtual APPN controllers.

*NO The system does not allow APPC sessions


or devices to use virtual APPN controllers.
If sessions are using HPR transport
tower support, they will use virtual APPN
controllers regardless of this setting.

*YES The system does allow APPC sessions or


devices to use virtual APPN controllers.

ALLOW_HPR_TRANSPORT_ HPR_TOWER VARCHAR(4) The HPR transport tower support value is used for
TOWER APPN session traffic.

*NO The system does not allow HPR transport


tower support to be used with APPN session
traffic.

*YES The system allows HPR transport tower


support to be used with APPN session
traffic.

AUTOCREATE_APPC_DEVICE_ APPC_LIMIT INTEGER The APPC device limit used for auto-creation of
LIMIT devices on virtual APPN controllers.

NETWORK_PRIORITY_TIMER NET_TIMER INTEGER The amount of time, in minutes, to allow for a path
switch attempt of a Rapid Transport Protocol (RTP)
Nullable connection that has network transmission priority.
Contains the null value if no path switch is allowed.

HIGH_PRIORITY_TIMER HIGH_TIMER INTEGER The amount of time, in minutes, to allow for a path
switch attempt of an RTP connection that has high
Nullable transmission priority.
Contains the null value if no path switch is allowed.

Database performance and query optimization 583


Table 126. NETWORK_ATTRIBUTE_INFO view (continued)

Column Name System Column Name Data Type Description

MEDIUM_PRIORITY_TIMER MED_TIMER INTEGER The amount of time, in minutes, to allow for a


path switch attempt of an RTP connection that has
Nullable medium transmission priority.
Contains the null value if no path switch is allowed.

LOW_PRIORITY_TIMER LOW_TIMER INTEGER The amount of time, in minutes, to allow for a path
switch attempt of an RTP connection that has low
Nullable transmission priority.
Contains the null value if no path switch is allowed.

ALLOW_ADD_TO_CLUSTER ADD_CLUST VARCHAR(7) Whether this system will allow another system to add
it as a node in a cluster.

*ANY Any other system can add this system


as a node in a cluster.

*NONE No other system can add this system as


a node in a cluster.

*RQSAUT Any other system can add this system


as a node in a cluster only after
the cluster add request has been
authenticated.

MODEM_COUNTRY_OR_ MODEM_ID CHAR(2) The country or region identifier associated with a


REGION_ID modem.
Nullable
This defines the country or region-specific default
characteristics for modems that are internal to IBM i
I/O adapters. This value must be configured correctly
to ensure proper operation and, in some countries
or regions, meet legal requirements. The adapter will
fail the vary on of the line if the modem country or
region ID is not set.
Contains the null value if no country or region
identifier has been defined.

Example
• Review the system network attributes.

SELECT * FROM QSYS2.NETWORK_ATTRIBUTE_INFO;

OBJECTCONNECT_INFO view
The OBJECTCONNECT_INFO view returns information about the ObjectConnect over IP server.
This view will only return data if Option 22 of the IBM i operating system is installed.
Authorization: None required.
The following table describes the columns in the view. The system name is OBJC_INFO. The schema is
QSYS2.
Table 127. OBJECTCONNECT_INFO view

Column Name System Column Name Data Type Description

STATE STATE VARCHAR(8) The state of the ObjectConnect over IP server.

ACTIVE The ObjectConnect over IP server is


active.

INACTIVE The ObjectConnect over IP server is


not active.

584 IBM i: Performance and Query Optimization


Table 127. OBJECTCONNECT_INFO view (continued)

Column Name System Column Name Data Type Description

AUTO_START AUTO_START VARCHAR(3) Whether the ObjectConnect over IP server is started


automatically.

NO The ObjectConnect over IP server is not


started automatically.

YES The ObjectConnect over IP server is started


automatically.

MINIMUM_JOBS MIN_JOBS INTEGER The minimum number of server jobs.

MAXIMUM_JOBS MAX_JOBS INTEGER The maximum number of server jobs.

INACTIVE_TIME INACT_TIME INTEGER The length of time, in minutes, a server job keeps
inactive before the server job ends.

SEND_BUFFER SND_BUF INTEGER The size of the TCP send buffer, in bytes, that the data
connection will use to send data over the network.

RECEIVE_BUFFER RCV_BUF INTEGER The size of the TCP receive buffer, in bytes, that the
data connection will use to receive data from the
network.

SUBSYSTEM_DESCRIPTION_ SBSD_LIB VARCHAR(10) The library containing the subsystem description.


LIBRARY

SUBSYSTEM_DESCRIPTION SBSD VARCHAR(10) The subsystem in which the ObjectConnect servers


run.

AUTHENTICATION_TYPE AUTH_TYPE VARCHAR(8) The type of authentication that the ObjectConnect


over IP server can use.

ANY The ObjectConnect over IP


server can use any of the
supported authentication types
to authenticate an incoming
ObjectConnect connection request.

KERBEROS The ObjectConnect over IP server


can use Kerberos to authenticate an
incoming ObjectConnect connection
request.

PASSWORD The ObjectConnect over IP server


can use the user profile and
password to authenticate an
incoming ObjectConnect connection
request.

Example
• List information about the ObjectConnect over IP server.

SELECT * FROM QSYS2.OBJECTCONNECT_INFO;

PING table function


The PING table function tests connectivity to a remote system.
This function is similar to the PING or Verify TCP/IP Connection (VFYTCPCNN) CL command.
Authorization: See Note below.

Database performance and query optimization 585


PING (
remote-system
REMOTE_SYSTEM =>

, remote-ip-address
REMOTE_IP_ADDRESS =>

, address-version-format
ADDRESS_VERSION_FORMAT =>

, number-packets-to-send
NUMBER_PACKETS_TO_SEND =>

, packet-length-to-send
PACKET_LENGTH_TO_SEND =>

, wait-time
WAIT_TIME =>

)
, local-ip-address
LOCAL_IP_ADDRESS =>

The schema is SYSTOOLS.

remote- A character string containing the name of the remote system with which the ping
system operation takes place. Can contain the following special value:

*INTNETADR The remote-ip-address parameter identifies the remote system.

If this parameter is omitted, the default value is *INTNETADR and a value for remote-ip-
address must be specified.
remote-ip- A character string that specifies the remote internet address. Either a valid IP Version 4
address or IP Version 6 address is accepted.
If remote-system contains a value other than *INTNETADR, this parameter is ignored.
address- A character string that specifies how the host name specified for remote-system is to be
version- resolved. It is also the address format to be used if remote-ip-address is specified.
format
*CALC The host name resolution method will be determined based on the host name
entered for remote-system. This is the default.
*IP4 Use the IP Version 4 host name resolution method.
*IP6 Use the IP Version 6 host name resolution method.

number- An integer value that specifies the number of packets that are sent to the remote system.
packets-to- Valid values are 1 to 999. The default is 5.
send

586 IBM i: Performance and Query Optimization


packet- An integer value that specifies the packet length (in bytes) to be sent to the remote
length-to- system. Valid values are 8 to 65500. The default is 256.
send
wait-time An integer value that specifies the number of seconds to wait for the return (echo)
packet before declaring a packet transfer a failure. Valid values are 1 to 120. The default
is 1.
local-ip- A character string that specifies the local internet address of the interface that the
address outbound packets are to use. Either a valid IP Version 4 or IP Version 6 address is
accepted. *ANY indicates that any interface's local internet address can be used. The
default is *ANY.

The result of the function is a table containing one row with the format shown in the following table. All
the columns are null capable.
Table 128. PING table function

Column Name Data Type Description

RESULT VARCHAR(7) The result of the ping request.

FAILURE At least one packet did not respond or an error occurred with the
command.

SUCCESS All packets responded.

PERCENT_SUCCESSFUL INTEGER The percent of successful packet responses.

PACKETS_SENT INTEGER The total number of packets that were sent.

RESPONSES_RETURNED INTEGER The total number of responses received for the packets that were sent.

ROUND_TRIP_AVG INTEGER The average time, in milliseconds, for a response.

ROUND_TRIP_MIN INTEGER The shortest time, in milliseconds, for a response.

ROUND_TRIP_MAX INTEGER The longest time, in milliseconds, for a response.

REMOTE_HOST_NAME VARCHAR(255) The name of the host that was the target of the ping request.

REMOTE_IP_ADDRESS VARCHAR(45) The IP address for REMOTE_HOST_NAME.

Note
This function is provided in the SYSTOOLS schema as an example of how messages in a job log can be
examined to gather status information. Similar to other Db2 for i provided tools within SYSTOOLS, the
SQL source can be extracted and used as a model for building similar helper functions, or to create a
customized version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
• Verify connectivity to a remote system by name.

SELECT * FROM TABLE(SYSTOOLS.PING('REMOTESYS'));

• Verify connectivity to a remote system by IP address.

SELECT * FROM TABLE(SYSTOOLS.PING(REMOTE_IP_ADDRESS => '9.1.2.3'));

Database performance and query optimization 587


RDB_ENTRY_INFO view
The RDB_ENTRY_INFO view returns information about relational database (RDB) directory entries.
The values returned for the columns in the view are similar to the values returned by the Display RDB
Directory Entries (DSPRDBDIRE) CL command.
Authorization: None required.
The following table describes the columns in the view. The system name is RDB_INFO. The schema is
QSYS2.
Table 129. RDB_ENTRY_INFO view

Column Name System Column Name Data Type Description

RDB_NAME RDB_NAME VARCHAR(18) The name of the relational database.

RDB_ALIAS RDB_ALIAS VARCHAR(18) The RDB alias name.

Nullable Contains the null value if no RDB alias is defined.

REMOTE_LOCATION_TYPE RMT_TYPE VARCHAR(4) The remote location type.

Nullable *IP The RDB is found using a host name


or an internet address over a TCP/IP
connection.

*SNA The RDB is accessed using a Systems


Network Architecture (SNA) address
and protocol.

Contains the null value if the value does not


apply.

REMOTE_LOCATION RMT_LOC VARCHAR(254) The remote location name of the system on


which the RDB is located.

remote- The remote location name is in


location- one of the following formats:
name
• SNA remote location name
(LU name).
• SNA remote network
identifier and remote
location name separated by
a period.
• IPv4 address in dotted
decimal form.
• IPv6 address in colon
hexadecimal form.
• IP host domain name.

*ARDPGM The RDB is accessed by using


the Application Requester
Driver (ARD) program.

*LOCAL The system database on this


system.

LOOPBACK This value is an alias for the IP


address of the host system.

*MIRROR The RDB is accessed on the


other system for a Db2 Mirror
relationship.

TEXT_DESCRIPTION TEXT VARGRAPHIC(50) CCSID The text description for this relational database
1200 entry.

Nullable Contains the null value is there is no descriptive


text.

588 IBM i: Performance and Query Optimization


Table 129. RDB_ENTRY_INFO view (continued)

Column Name System Column Name Data Type Description

REMOTE_PORT_OR_SERVICE RMT_PORT VARCHAR(14) The relational database entry port number or


service name that is used at the remote location
Nullable to communicate with the system on which
the RDB is located. If *DRDA was specified,
the Distributed Relational Database Architecture
(DRDA) port is 446.
Contains the null value if
REMOTE_LOCATION_TYPE is not *IP.

PREFERRED_AUTHENTICATION PREF_AUTH VARCHAR(10) The preferred authentication method on a


connection request.
Nullable
*ENCUSRPWD Encrypted user ID and
encrypted password.

*KERBEROS Authentication occurs using


Kerberos.

*USRENCPWD User ID and encrypted


password.

*USRID User ID only.

*USRIDPWD User ID and password.

Contains the null value if


REMOTE_LOCATION_TYPE is not *IP.

LOWER_AUTHENTICATION LOWER_AUTH VARCHAR(11) Whether an authentication method lower than


what was specified for the preferred method will
Nullable be accepted during negotiation with the server.

*ALWLOWER Allow negotiation of a lower


authentication method.

*NOALWLOWER Do not allow negotiation


of a lower authentication
method.

Contains the null value if


REMOTE_LOCATION_TYPE is not *IP.

ENCRYPTION_ALGORITHM ENCRYPTION VARCHAR(4) The encryption algorithm to be used initially on


the connection request.
Nullable
*AES Advanced Encryption Standard (AES) is
to be used initially.

*DES Data Encryption Standard (DES) is to


be used initially.

Contains the null value if the encryption


algorithm does not apply.

SECURE_CONNECTION SECURE VARCHAR(5) Whether Transport Layer Security (TLS) is to


be used on a DDM/DRDA TCP/IP connection
Nullable request.

*NONE TLS is not used.

*TLS TLS is used.

Contains the null value if


REMOTE_LOCATION_TYPE is not *IP.

APPC_DEVICE_DESCRIPTION APPC_DEVD VARCHAR(10) The Advanced Program-to-Program


Communications (APPC) device description on
Nullable this system that is used with this RDB entry. Can
contain the special value:

*LOC If APPC is being used, the system


determines which device description is
used.

Contains the null value if


REMOTE_LOCATION_TYPE is not *SNA.

Database performance and query optimization 589


Table 129. RDB_ENTRY_INFO view (continued)

Column Name System Column Name Data Type Description

LOCAL_LOCATION LOCAL_LOC VARCHAR(8) The local location name by which this system
is identified to the system on which the RDB is
Nullable located. Can contain one of the following special
values:

*LOC If APPC is being used, the system


determines which local location
name is used.

*NETATR The LCLLOCNAME value specified


in the system network attributes is
used.

Contains the null value if


REMOTE_LOCATION_TYPE is not *SNA.

REMOTE_NETWORK_ID RMT_NETID VARCHAR(8) The remote network identifier of the system on


which the RDB is located. Can contain one of the
Nullable following special values:

*LOC If APPC is being used, the system


determines which remote network
identifier is used.

*NETATR The remote network identifier


specified in the network attributes
is used.

*NONE No remote network identifier is


used.

Contains the null value if


REMOTE_LOCATION_TYPE is not *SNA.

REMOTE_MODE RMT_MODE VARCHAR(8) The mode name to use with the remote location
name to communicate with the system on which
Nullable the RDB is located. Can contain one of the
following special values:

*NETATR The mode in the network


attributes is used.

BLANK A mode name of all blanks is used.

Contains the null value if


REMOTE_LOCATION_TYPE is not *SNA.

TRANSACTION_PROGRAM TRANS_PGM VARCHAR(8) FOR BIT The name of the transaction program to use with
DATA the RDB entry.

Nullable transaction- The transaction program


program- name is in one of the following
name formats:
• A 4-byte hexadecimal
name. For example,
X'07F6C4C2'.
• An 8-byte character name.
• The value *DRDA, which
means the Distributed
Relational Database
Architecture™ (DRDA)
transaction program name
is used, X'07F6C4C2'.

Contains the null value if


REMOTE_LOCATION_TYPE is not *SNA.

ARD_LIBRARY ARD_LIB VARCHAR(10) The library containing the Application Requester


Driver (ARD) program. Can contain the special
Nullable values *LIBL or *CURLIB.
Contains the null value if REMOTE_LOCATION is
not *ARDPGM.

ARD_PROGRAM ARD_PGM VARCHAR(10) The ARD program to be called to process SQL


requests directed to the RDB.
Nullable
Contains the null value if REMOTE_LOCATION is
not *ARDPGM.

590 IBM i: Performance and Query Optimization


Example
• Find any RDBs that might be sending authentication data in the clear

SELECT * FROM QSYS2.RDB_ENTRY_INFO


WHERE PREFERRED_AUTHENTICATION IN ('*USRID', '*USRIDPWD', '*USRENCPWD');

REMOVE_TIME_SERVER procedure
The REMOVE_TIME_SERVER procedure removes a Network Time Protocol (NTP) server from the NTP
configuration list.
The REMOVE_TIME_SERVER procedure requires 5770SS1 Option 33 - Portable Application Solutions
Environment (PASE).
Authorization: The caller must have:
• *IOSYSCFG special authority, and
• *RW authority to /QIBM/UserData/OS400/TCPIP/NTP/ntp.conf

REMOVE_TIME_SERVER ( time-server )
TIME_SERVER =>

The schema is QSYS2.

time-server A character or graphic string that identifies the DNS name of the NTP server to be removed
from the configuration.

Example
• Remove time.domain.name.com as a preferred time server

CALL QSYS2.REMOVE_TIME_SERVER(TIME_SERVER =>'time.domain.name.com');

SERVER_SBS_CONFIGURATION view
The SERVER_SBS_CONFIGURATION view returns subsystem routing information for some IBM i servers.
When a client attempts to use TCP/IP to form a connection to a server listed in this view, an attempt is
made to attach to a prestart job in the subsystem configured for that server.
The information returned by this view is similar to the information shown by IBM Navigator for i in
Network > Servers. For information about users who have alternate subsystem configurations for some
IBM i servers, see “SERVER_SBS_ROUTING view” on page 592.
The QSYS2.SET_SERVER_SBS_ROUTING procedure can be used to modify entries shown in this view.
Authorization: None required.
The following table describes the columns in the view. The system name is SERVER_CFG. The schema is
QSYS2.
Table 130. SERVER_SBS_CONFIGURATION view

System Column
Column Name Name Data Type Description

SERVER_NAME SERVER VARCHAR(10) The server name for this entry.

SERVER_SEARCH_ORDER SEARCH_ORD INTEGER The search order for selecting this subsystem routing entry. The
order starts with one for each SERVER_NAME value.
Nullable
Contains the null value for the default entry for each server. This is
the entry that will be selected if no other specific entry is selected.

SUBSYSTEM SUBSYSTEM VARCHAR(10) The subsystem name that incoming connections for this server
will be rerouted to when this entry is selected.

Database performance and query optimization 591


Table 130. SERVER_SBS_CONFIGURATION view (continued)

System Column
Column Name Name Data Type Description

ALLOW_ROLLOVER ROLLOVER VARCHAR(3) Indicates how incoming connection requests are handled if the
subsystem is not active.

NO Incoming connections will be rejected.

YES Incoming connections will be routed to a batch immediate


job in the subsystem where the server daemon job is
active.

IP_ADDRESS_TYPE ADDR_TYPE CHAR(4) The type of IP address for IP_ADDRESS_START and


IP_ADDRESS_END.
Nullable
IPV4 The addresses are IPv4 addresses.

IPV6 The addresses are IPv6 addresses.

Contains the null value if no IP addresses are used for defining


this row.

IP_ADDRESS_START IP_START VARCHAR(45) The IP address for alternate routing or the starting IP address for
a range of IP addresses.
Nullable
Contains the null value if no IP addresses are used for defining
this row.

IP_ADDRESS_END IP_END VARCHAR(45) The ending IP address for a range of IP addresses.

Nullable Contains the null value if this row is not for a range of IP
addresses.

SUBNET_MASK SUBNET VARCHAR(15) The actual value of the subnet mask in dotted-decimal notation.

Nullable Contains the null value if IP_ADDRESS_START is null, there is no


subnet mask, or this is an IPv6 address.

PREFIX_LENGTH PREFIX INTEGER The prefix length defines how many of the left-most bits of the
IPv6 address make up the prefix.
Nullable
Contains the null value if IP_ADDRESS_START is null or an IPv4
address.

TEXT_DESCRIPTION TEXT VARCHAR(50) Descriptive text for this entry.

Nullable Contains the null value if there is no descriptive text.

Example
List all the servers that have alternate subsystems defined.

SELECT * FROM QSYS2.SERVER_SBS_CONFIGURATION


ORDER BY SERVER_NAME, SERVER_SEARCH_ORDER;

SERVER_SBS_ROUTING view
The SERVER_SBS_ROUTING view returns information about the users who have alternate subsystem
configurations for some IBM i servers. When a user profile listed in this view attempts to use TCP/IP to
form a connection to the server, an attempt is made to use the alternate subsystem instead of the default
subsystem for that server.
For subsystem routing information for some IBM i servers, see “SERVER_SBS_CONFIGURATION view” on
page 591.
The QSYS2.SET_SERVER_SBS_ROUTING procedure can be used to modify the values shown in this view.
Authorization: The caller must have *OBJOPR and *READ authority to the *USRPRF.
The following table describes the columns in the view. The system name is SRVR_RTG. The schema is
QSYS2.

592 IBM i: Performance and Query Optimization


Table 131. SERVER_SBS_ROUTING view

System Column
Column Name Name Data Type Description

AUTHORIZATION_NAME USER_NAME VARCHAR(128) The user profile that has an alternate subsystem configuration.

QRWTSRVR_SUBSYSTEM DRDADDMSBS VARCHAR(10) The subsystem name that incoming DRDA or DDM connections
will be rerouted to.
Nullable
Contains the null value when an alternate subsystem for this
server has not been configured for this user.

QZDASOINIT_SUBSYSTEM ZDASBS VARCHAR(10) The subsystem name that incoming database server connections
will be rerouted to.
Nullable
Contains the null value when an alternate subsystem for this
server has not been configured for this user.

QZRCSRVS_SUBSYSTEM ZRCSBS VARCHAR(10) The subsystem name that incoming remote command server
connections will be rerouted to.
Nullable
Contains the null value when an alternate subsystem for this
server has not been configured for this user.

QZHQSSRV_SUBSYSTEM ZHQSBS VARCHAR(10) The subsystem name that incoming data queue server
connections will be rerouted to.
Nullable
Contains the null value when an alternate subsystem for this
server has not been configured for this user.

QZSCSRVS_SUBSYSTEM ZSCSBS VARCHAR(10) The subsystem name that incoming central server connections
will be rerouted to.
Nullable
Contains the null value when an alternate subsystem for this
server has not been configured for this user.

QNPSERVS_SUBSYSTEM NPSSBS VARCHAR(10) The subsystem name that incoming network print server
connections will be rerouted to.
Nullable
Contains the null value when an alternate subsystem for this
server has not been configured for this user.

QPWFSERVSO_SUBSYSTEM PWFSBS VARCHAR(10) The subsystem name that incoming file server connections will be
rerouted to.
Nullable
Contains the null value when an alternate subsystem for this
server has not been configured for this user.

QDBMSRVR_SUBSYSTEM DBMSBS VARCHAR(10) The subsystem name that incoming database mirror connections
will be rerouted to.
Nullable
Contains the null value when an alternate subsystem for this
server has not been configured for this user.

QRWTSRVR_ROLLOVER DRDA_RO VARCHAR(3) Indicates how incoming DRDA or DDM connection requests are
handled if the specified subsystem cannot be used.

NO Incoming connections will be rejected.

YES Incoming connections will be routed to the default


subsystem. If an alternate subsystem is not configured for
this server, YES is the default.

QZDASOINIT_ROLLOVER ZDA_RO VARCHAR(3) Indicates how incoming database server connection requests are
handled if the specified subsystem cannot be used.

NO Incoming connections will be rejected.

YES Incoming connections will be routed to the default


subsystem. If an alternate subsystem is not configured for
this server, YES is the default.

QZRCSRVS_ROLLOVER ZRC_RO VARCHAR(3) Indicates how incoming remote command connection requests
are handled if the specified subsystem cannot be used.

NO Incoming connections will be rejected.

YES Incoming connections will be routed to the default


subsystem. If an alternate subsystem is not configured for
this server, YES is the default.

Database performance and query optimization 593


Table 131. SERVER_SBS_ROUTING view (continued)

System Column
Column Name Name Data Type Description

QZHQSSRV_ROLLOVER ZHQ_RO VARCHAR(3) Indicates how incoming data queue server connection requests
are handled if the specified subsystem cannot be used.

NO Incoming connections will be rejected.

YES Incoming connections will be routed to the default


subsystem. If an alternate subsystem is not configured for
this server, YES is the default.

QZSCSRVS_ROLLOVER ZSC_RO VARCHAR(3) Indicates how incoming central server connection requests are
handled if the specified subsystem cannot be used.

NO Incoming connections will be rejected.

YES Incoming connections will be routed to the default


subsystem. If an alternate subsystem is not configured for
this server, YES is the default.

QNPSERVS_ROLLOVER NPS_RO VARCHAR(3) Indicates how incoming network print server connection requests
are handled if the specified subsystem cannot be used.

NO Incoming connections will be rejected.

YES Incoming connections will be routed to the default


subsystem. If an alternate subsystem is not configured for
this server, YES is the default.

QPWFSERVSO_ROLLOVER PWF_RO VARCHAR(3) Indicates how incoming file server connection requests are
handled if the specified subsystem cannot be used.

NO Incoming connections will be rejected.

YES Incoming connections will be routed to the default


subsystem. If an alternate subsystem is not configured for
this server, YES is the default.

QDBMSRVR_ROLLOVER DBM_RO VARCHAR(3) Indicates how incoming database mirror connection requests are
handled if the specified subsystem cannot be used.

NO Incoming connections will be rejected.

YES Incoming connections will be routed to the default


subsystem. If an alternate subsystem is not configured for
this server, YES is the default.

The following table shows the servers that can have alternate subsystem configurations.

Table 132. Servers and server names


Server Description Server Name
Central server QZSCSRVS
Database server QZDASOINIT
Data queue server QZHQSSRV
Db2 Mirror server QDBMSRVR
DDM QRWTSRVR
DRDA QRWTSRVR
File server QPWFSERVSO
Network print server QNPSERVS
Remote command server QZRCSRVS

Example

594 IBM i: Performance and Query Optimization


Query subsystem routing information for all user profiles:

SELECT * FROM QSYS2.SERVER_SBS_ROUTING

SET_SERVER_SBS_ROUTING procedure
The SET_SERVER_SBS_ROUTING procedure provides the ability to configure a server to use an alternate
subsystem. This can be for all users of the server, for a specific user profile, or by IP address.
This procedure allows an administrator to reposition certain connections to a server into an alternate,
non-default, subsystem. When configured, new incoming TCP/IP server connections will use the alternate
subsystem.
Connections to be re-routed can be defined three ways.
1. A server's default subsystem for all connections.
2. For an IP address or a range of IP addresses.
3. For a specific user profile. The user profile can be a group profile or a supplemental group profile.
Some servers do not support routing by specific user profile; refer to Table 133 on page 595 for
details.
To select the subsystem for a connection, the routing logic first looks for an IP address routing entry
for the server. If there is not one, it will route according to the defined default. The routing process will
then immediately check for a configured entry for the specific user profile and attempt to route to its
subsystem. For example, if a server is configured to route to a user-specified subsystem by incoming
TCP/IP address as well as by user profile, the job will first attempt to route to the subsystem configured
for that TCP/IP address and then immediately attempt to route to the subsystem configured for the
connecting user profile. Understanding this order of processing is key to recognizing failures that may
occur.
By default, all users for the following servers use the listed default subsystem:

Table 133. Servers and default subsystems


Supports routing Supports routing
Server Description Server Name Default subsystem by user by IP address
Central server QZSCSRVS QUSRWRK Yes Yes
Database server QZDASOINIT QUSRWRK Yes Yes
Data queue server QZHQSSRV QUSRWRK Yes Yes
Db2 Mirror server QDBMSRVR QUSRWRK Yes Yes
DDM QRWTSRVR QUSRWRK Yes Yes
DRDA QRWTSRVR QUSRWRK Yes Yes
File server QPWFSERVSO QSERVER Yes Yes
IBM i NetServer QZLSFILE QSERVER No Yes
Network print QNPSERVS QUSRWRK Yes Yes
server
Remote command QZRCSRVS QUSRWRK Yes Yes
server
Sign-on server QZSOSIGN QUSRWRK No Yes

For more information on these servers see DRDA and DDM overview and Host servers by function.
Routing information set by this procedure can be queried using the following views:
• For routing for a specific user, see “SERVER_SBS_ROUTING view” on page 592.

Database performance and query optimization 595


• For routing that applies to all users and IP addresses, see “SERVER_SBS_CONFIGURATION view” on
page 591.
Authorization:
• When authorization-name specifies a user profile, the caller must have:
– *SECADM special authority, and
– *OBJMGT and *USE authorities to the user profile.
• When authorization-name is *ALL, the caller must have *IOSYSCFG special authority.

596 IBM i: Performance and Query Optimization


SET_SERVER_SBS_ROUTING (
AUTHORIZATION_NAME =>

authorization-name , server-name ,
SERVER_NAME =>

subsystem-name
SUBSYSTEM_NAME =>

, allow-rollover
ALLOW_ROLLOVER =>

, ip-address-start
IP_ADDRESS_START =>

, ip-address-end
IP_ADDRESS_END =>

, subnet-mask
SUBNET_MASK =>

, prefix-length
PREFIX_LENGTH =>

, server-position
SERVER_POSITION =>

, replacement-ip-address-start
REPLACEMENT_IP_ADDRESS_START =>

, replacement-ip-address-end
REPLACEMENT_IP_ADDRESS_END =>

)
, text-description
TEXT_DESCRIPTION =>

The schema is QSYS2.

authorization- A character or graphic string expression that identifies an existing user or group profile
name name. Can contain the following special value:

*ALL This configuration applies to all users of the server unless a specific alternate
subsystem is defined for the user. To route using an IP address, *ALL must be
specified.

Database performance and query optimization 597


server-name A character or graphic string expression that identifies the name of the server job that
will be rerouted to subsystem-name for all users or for authorization-name whenever a
connection is initiated to this server job. Valid server-name values are:
• QDBMSRVR
• QNPSERVS
• QPWFSERVSO
• QRWTSRVR
• QZDASOINIT
• QZHQSSRV
• QZLSFILE
• QZRCSRVS
• QZSCSRVS
• QZSOSIGN
The special value of *ALL can be used to indicate all of the server-name values that
support routing by user, listed in Table 133 on page 595. *ALL is not allowed if
authorization-name is *ALL.
subsystem- A character or graphic string expression that identifies the name of the subsystem that
name will be used, instead of the default subsystem, whenever a connection is initiated to
the specified server job. No validation is done on subsystem-name to make sure it is a
valid and active subsystem.
If subsystem-name is the null value:
• When authorization-name is not *ALL, the configuration entry for the server-name
for this authorization-name will be cleared. The default subsystem will revert to the
system supplied default as shown in Table 133 on page 595.
• When authorization-name is *ALL:
– If ip-address-start is not specified, the configuration entry for the server-name will
be removed, reverting incoming connections to use the default subsystem.
– If ip-address-start is specified, the configuration entry identified by the server-
name and the specified ip-address-start will be removed.

allow-rollover A character or graphic string expression that indicates the action to take if the
specified subsystem is not active. Valid values are:
NO If the alternate subsystem cannot be used, the connection request will fail.
YES If the alternate subsystem cannot be used, the connection request will succeed
by using a batch immediate job in the default subsystem.

If this parameter is not specified, the default is YES.

When routing for the server (authorization-name is *ALL), the following parameters are allowed:

ip-address- A character or graphic string expression that identifies an IPv4 or IPv6 address for a
start single client.
• If ip-address-end is not specified, this is a specific IPv4 or IPv6 address.
• If ip-address-end is specified, this is the start value for a range of IPv4 or IPv6
addresses for a group of clients. When more than one range of addresses is defined
for a server, the IP address ranges cannot overlap.
When ip-address-start is specified, either subnet-mask or prefix-length can be
specified.

598 IBM i: Performance and Query Optimization


This parameter can only be specified when authorization-name is *ALL. If this
parameter is not specified, the default is the null value, meaning that the connection
will not be routed by IP address.
ip-address- A character or graphic string expression that identifies the end value for a range of
end IPv4 or IPv6 addresses for a group of clients. This parameter can only be specified if
ip-address-start is specified.
This parameter can only be specified when authorization-name is *ALL. If this
parameter is not specified, the default is the null value.
subnet-mask A character or graphic string expression that identifies the IPv4 subnet mask.
This parameter can only be specified when authorization-name is *ALL. subnet-mask
cannot be specified if prefix-length is specified.
prefix-length An integer value that defines how many bits of the IPv6 address are in the prefix.
When this parameter is specified with a non-zero value, the IP address parameters are
treated as IPv6 addresses. It is required for an IPv6 address.
This parameter can only be specified when authorization-name is *ALL. prefix-length
cannot be specified if subnet-mask is specified.
server-position An integer value that indicates the position for this entry for server-name
in the list returned by the QSYS2.SERVER_SBS_CONFIGURATION view in the
SERVER_SEARCH_ORDER column. This value represents the search order to be used
when determining which entry to use for routing.
This entry will be added at the specified position in the list for server-name. An
existing entry at this position and all later entries will have their search order position
incremented by one. If this value is greater than the current number of entries for the
server, this entry will be added to the end of the server's list.
This parameter can only be specified when authorization-name is *ALL. If this
parameter is not specified, the default is the null value. This means that a new entry
will be added to the end of the list, and a change to an existing IP address entry will
remain in its current position.
replacement- A character or graphic string expression that identifies a replacement IPv4 or IPv6
ip-address- address for the specified ip-address-start address. ip-address-start must already be
start configured for this server.
This parameter can only be specified when authorization-name is *ALL. If this
parameter is not specified, the default is the null value.
replacement- A character or graphic string expression that identifies a replacement IPv4 or IPv6
ip-address- address for the specified ip-address-end address. ip-address-end must already be
end configured for this server.
This parameter can only be specified when authorization-name is *ALL. If this
parameter is not specified, the default is the null value.
text- A character or graphic string expression describing this configuration.
description This parameter can only be specified when authorization-name is *ALL. If this
parameter is not specified, the default is the null value.

Notes
The prestart job entry must specify the subsystem-name.
When ALLOW_ROLLOVER is YES: if, for any reason, the alternate subsystem cannot be used to establish
the connection, the connection will run in the default subsystem (or the last subsystem it was successfully
routed to) as a batch immediate job. An example of this would be if the authorization-name does not have
*USE authority to the subsystem description for subsystem-name.

Database performance and query optimization 599


If routing has been configured for a user profile, the user profile configuration will always be used,
regardless of any group profile configuration or a subsystem configuration for *ALL. A group profile
configuration will take precedence over any supplemental group profile configuration.

Examples
• Set new incoming DRDA and DDM TCP/IP server connections for user profile TIM to route to subsystem
TIMSUBSYS.

CALL QSYS2.SET_SERVER_SBS_ROUTING('TIM','QRWTSRVR','TIMSUBSYS')

• Reset incoming DRDA and DDM TCP/IP server connections for user profile TIM back to the original
default subsystem.

CALL QSYS2.SET_SERVER_SBS_ROUTING('TIM','QRWTSRVR',NULL)

• Configure group profile ADMIN to use an alternate subsystem for all of the servers supported by this
procedure. Do not permit a connection request to rollover to use QUSRWRK.

CALL QSYS2.SET_SERVER_SBS_ROUTING('ADMIN','*ALL','ADHOCSBS','NO')

• Set new incoming Database server TCP/IP connections for user profile BOB to route to subsystem
BOBSUBSYS.

CALL QSYS2.SET_SERVER_SBS_ROUTING('BOB','QZDASOINIT','BOBSUBSYS')

• Construct a subsystem that will constrain the amount of system resources available to users who are
known to execute expensive queries.

CRTSBSD SBSD(QGPL/ADHOCSBS) POOLS((1 *BASE)) TEXT('Adhoc DRDA users SBS')

CRTCLS CLS(QGPL/ADHOCCLS) RUNPTY(55) TIMESLICE(100) TEXT('Adhoc DRDA users class')

ADDPJE SBSD(QGPL/ADHOCSBS) PGM(QSYS/QRWTSRVR) JOBD(QGPL/QDFTSVR) CLS(QGPL/ADHOCCLS)

STRSBS SBSD(QGPL/ADHOCSBS)

CALL QSYS2.SET_SERVER_SBS_ROUTING('SLFUSER','QRWTSRVR','ADHOCSBS')

• Set all Db2 Mirror connections to run in subsystem QDBMWRK. This separates the jobs from the
default QUSRWRK subsystem. Make sure the pool for the subsystem description has sufficient memory
available.

CRTSBSD SBSD(QSYS/QDBMWRK) POOLS((1 *BASE))

ADDPJE SBSD(QDBMWRK) PGM(QSYS/QDBMSRVR) USER(QUSER) STRJOBS(*YES) INLJOBS(50) THRESHOLD(20)


ADLJOBS(40) MAXJOBS(*NOMAX) JOB(*PGM) JOBD(QSYS/QDBMSRVR) MAXUSE(*NOMAX) WAIT(*YES)
POOLID(1) CLS(QSYS/QSYSCLS20 *CALC *NONE *CALC)

STRSBS QSYS/QDBMWRK

CALL QSYS2.SET_SERVER_SBS_ROUTING('*ALL','QDBMSRVR','QDBMWRK')

• Define a complete block of IP addresses to be routed to subsystem NEWSBS for QZDASOINIT jobs. The
range includes all addresses in the address block of 192.168.1.0-255

CALL QSYS2.SET_SERVER_SBS_ROUTING(AUTHORIZATION_NAME => '*ALL',


SERVER_NAME => 'QZDASOINIT',
IP_ADDRESS_START => '192.168.1.0',
SUBNET_MASK => '255.255.255.0'
SUBSYSTEM_NAME => 'NEWSBS')

• Define a range of IP addresses for QZDASOINIT jobs to be routed to a subsystem NEWSBS.

CALL QSYS2.SET_SERVER_SBS_ROUTING(AUTHORIZATION_NAME => '*ALL',


SERVER_NAME => 'QZDASOINIT',
IP_ADDRESS_START => '192.168.1.10',

600 IBM i: Performance and Query Optimization


IP_ADDRESS_END => '192.168.1.30',
SUBSYSTEM_NAME => 'NEWSBS')

• Change the range of IP addresses for QZDASOINIT jobs that are routed to a subsystem NEWSBS.

CALL QSYS2.SET_SERVER_SBS_ROUTING(AUTHORIZATION_NAME => '*ALL',


SERVER_NAME => 'QZDASOINIT',
IP_ADDRESS_START => '192.168.1.10',
IP_ADDRESS_END => '192.168.1.30',
REPLACEMENT_IP_ADDRESS_START => '192.168.1.10',
REPLACEMENT_IP_ADDRESS_END => '192.168.1.100',
SUBSYSTEM_NAME => 'NEWSBS')

• Remove a range of IP addresses for QZRCSRVS jobs.

CALL QSYS2.SET_SERVER_SBS_ROUTING(AUTHORIZATION_NAME => '*ALL',


SERVER_NAME => 'QZRCSRVS',
SUBSYSTEM_NAME => NULL,
IP_ADDRESS_START => '192.168.1.10',
IP_ADDRESS_END => '192.168.1.100')

• Add a new entry in the first position in the prioritized list of IP address routing entries for the
QPWFSERVSO server.

CALL QSYS2.SET_SERVER_SBS_ROUTING(AUTHORIZATION_NAME => '*ALL',


SERVER_NAME => 'QPWFSERVSO',
SUBSYSTEM_NAME => 'SBS1',
IP_ADDRESS_START => '192.168.2.20',
SERVER_POSITION => 1,
TEXT_DESCRIPTION => 'Top rule for QPWFSERVSO')

Related information
Use of prestart jobs

TCPIP_INFO view
The TCPIP_INFO view contains TCP/IP information for the current host connection.
Authorization: None required.
The following table describes the columns in the view. The schema is QSYS2.
Table 134. TCPIP_INFO view

Column Name System Column Name Data Type Description

COLLECTED_TIME COLLE00001 TIMESTAMP Timestamp indicating when this row of information was
collected.
Nullable

LOCAL_HOST_NAME LOCAL00001 VARCHAR(255) TCP/IP host name of the local system.

Nullable

CLIENT_IP_ADDRESS_TYPE CLIEN00001 VARCHAR(10) TCP/IP address version of the client.

Nullable

CLIENT_IP_ADDRESS CLIEN00002 VARCHAR(45) TCP/IP address of the client.

Nullable

CLIENT_PORT_NUMBER CLIEN00003 INTEGER TCP/IP port of the client.

Nullable

SERVER_IP_ADDRESS_TYPE SERVE00001 VARCHAR(10) TCP/IP address version of the server.

Nullable

SERVER_IP_ADDRESS SERVE00002 VARCHAR(45) TCP/IP address of the server.

Nullable

SERVER_PORT_NUMBER SERVE00003 INTEGER TCP/IP port number of the server.

Nullable

Database performance and query optimization 601


Table 134. TCPIP_INFO view (continued)

Column Name System Column Name Data Type Description

HOST_VERSION HOST_00001 VARCHAR(10) Operating system version.

Nullable

Example
Return information about the current host connection.

SELECT * FROM QSYS2.TCPIP_INFO

TIME_PROTOCOL_INFO view
The TIME_PROTOCOL_INFO view returns information about Network Time Protocol (NTP) servers that
are configured.
The TIME_PROTOCOL_INFO view requires 5770SS1 Option 33 - Portable Application Solutions
Environment (PASE).
Authorization: The caller must have *IOSYSCFG special authority.
The following table describes the columns in the view. The system name is TIME_PROTO. The schema is
QSYS2.
Table 135. TIME_PROTOCOL_INFO view

Column Name System Column Name Data Type Description

TIME_SERVER SERVER VARCHAR(256) The DNS domain name for the NTP server.

PREFERRED_INDICATOR PREFERRED VARCHAR(3) Indicates whether this server is a preferred time


source in the NTP client configuration

NO This is not a preferred time server.

YES This is a preferred time server.

Example
• List all the configured time protocol servers.

SELECT * FROM QSYS2.TIME_PROTOCOL_INFO;

Configuration Services
These services provide configuration information.

HARDWARE_RESOURCE_INFO table function


The HARDWARE_RESOURCE_INFO table function returns information about configured hardware
resources.
The information returned is similar to the detail available through the STRSST Hardware Service Manager
interface and from the Retrieve Hardware Resource List (QGYRHRL, QgyRtvHdwRscList) and Retrieve
Hardware Resource Information (QGYRHRI, QgyRtvHdwRscInfo) APIs.
Authorization: None required.

602 IBM i: Performance and Query Optimization


HARDWARE_RESOURCE_INFO ( resource-category
RESOURCE_CATEGORY =>

, detailed-info
DETAILED_INFO =>

)
, ignore-errors
IGNORE_ERRORS =>

The schema is QSYS2.

resource- A character or graphic string expression that identifies the category of resource
category information to be returned.

ADAPTER Coupled system adapter resources


ALL Information for all resource categories
COMM Communication resources
CRYPTO Cryptographic resources
OPTICAL Optical resources
PROCESSOR Processor resources
STORAGE Storage device resources, including tape and optical resources
TAPE Tape resources
WORKSTATION Local workstation resources

detailed-info A character or graphic string expression that indicates the type of information to be
returned.

NO Only the basic information is returned for the resource. This is the information in
the columns prior to the SERIAL_NUMBER column. This is the default.
YES All the information available for the resource is returned.

ignore-errors A character or graphic string expression that identifies what to do when an error is
encountered.

NO An error is returned.

YES A warning is returned.


No row is returned when an error is encountered. This is the default.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 136. HARDWARE_RESOURCE_INFO table function

Column Name Data Type Description

ID INTEGER A generated unique identifier for this row in the result set.

PARENT_ID INTEGER The ID of the parent to this resource.


Contains the null value if this resource is not a child of another
resource.

Database performance and query optimization 603


Table 136. HARDWARE_RESOURCE_INFO table function (continued)

Column Name Data Type Description

RESOURCE_CATEGORY VARCHAR(11) The hardware resource category of the resource for which information
is returned.

ADAPTER Coupled system adapter resources.

COMM Communication resources.

CRYPTO Cryptographic resources.

OPTICAL Optical resources.

PROCESSOR Processor resources.

STORAGE Storage device resources.

TAPE Tape resources.

WORKSTATION Local workstation resources.

RESOURCE_NAME VARCHAR(10) The name of the resource.

STATUS VARCHAR(12) Whether the resource is operational.

INOPERATIVE Resource is not operational.

NOT DETECTED Presence of resource could not be detected.

OPERATIONAL Resource is operational.

Contains the null value if STATUS does not apply to this resource or
could not be determined.

EXTENDED_STATUS VARCHAR(14) The extended hardware status of the resource.

DEGRADED Resource is operational but performance is


degraded.

DISABLED Resource is currently disabled.

ERROR Resource is operational but errors have been


detected.

FAILED Resource has failed.

INOPERATIVE Resource is not operational.

NO POWER Resource is powered off or no power is being


supplied to it.

NOT CONNECTED Resource is not connected.

NOT INSTALLED Resource is not installed.

OPERATIONAL Resource is operational.

SOFTWARE ERROR Resource is failed due to a system software


error.

Contains the null value if STATUS does not apply to this resource or
could not be determined.

DEVICE_TYPE VARCHAR(4) An identifier that represents the object type of this resource. For self-
configuring tape devices, this represents the emulated device type
number.
A value of *TAP indicates that a self-configuring tape device is
emulating a device type that contains characters outside the range of 0
to 9 and A to Z.
Contains the null value if a value is not available.

DEVICE_MODEL VARCHAR(3) The model number of the resource. For self-configuring tape devices,
this represents the emulated device model number.
Contains the null value if a value is not available.

ADAPTER_SYSTEM VARCHAR(8) The system to which the coupled system adapter is connected.
Contains the null value if a value is not available.

LAN_ADAPTER_ADDRESS VARCHAR(12) The network address of the LAN adapter resource.


Contains the null value if a value is not available.

604 IBM i: Performance and Query Optimization


Table 136. HARDWARE_RESOURCE_INFO table function (continued)

Column Name Data Type Description

LINE_TYPE VARCHAR(5) The line type of the LAN resource.

FDDI Fiber distributed data interface.

TOKEN Token ring.

Contains the null value if the resource has no line type.

TEXT_DESCRIPTION VARCHAR(50) The description of the resource.


Contains the null value if there is no descriptive text.

MESSAGE_ID CHAR(7) The message from which TEXT_DESCRIPTION is obtained. This


message is in the QCPFMSG message file in *LIBL.
Contains the null value if there is no descriptive text.

RESOURCE_KIND BINARY(24) The resource kind field consists of 24 bytes of hexadecimal numbers. It
can be divided into three 8-byte fields called Kind 1, Kind 2, and Kind 3.
The system uses Kind 1, Kind 2, and Kind 3 to categorize the resource.

RESOURCE_KIND1 BINARY(8) The value for Kind 1.

RESOURCE_KIND2 BINARY(8) The value for Kind 2.

RESOURCE_KIND3 BINARY(8) The value for Kind 3.

Non-null values can be returned for the following columns when DETAILED_INFO is YES

SERIAL_NUMBER VARCHAR(15) The expanded unique number based on the manufacturing sequence
for the resource.

SERIAL_NUMBER_SHORT VARCHAR(10) A unique number based on the manufacturing sequence for the
resource.

PART_NUMBER VARCHAR(12) A manufacturing identifier that represents similar types of hardware.


Contains the null value if the column does not apply to the resource.

BUS_NUMBER INTEGER A numerical representation of the path connection of the system


processor to the card.
Contains the null value if the column does not apply to the resource.

BOARD_NUMBER INTEGER A numerical representation of a section of the bus into which the card
is plugged.
Contains the null value if the column does not apply to the resource.

CARD_NUMBER INTEGER A numerical representation of the location of the card on the bus.
Contains the null value if the column does not apply to the resource.

CARD_POSITION VARCHAR(5) The physical location where the device or feature is plugged into the
bus.
Contains the null value if the column does not apply to the resource.

FRAME_ID VARCHAR(4) The identifier of a frame resource.


Contains the null value if the column does not apply to the resource.

Database performance and query optimization 605


Table 136. HARDWARE_RESOURCE_INFO table function

Column Name Data Type Description

LOCATION_CODE VARCHAR(79) The physical location of the hardware resource in the system.
The location code field is a sequence of 0 or more location labels that
when followed in order, lead to the resource location. This is the place
someone could go to view, remove, or replace the piece of hardware.
Location labels are etched, silk screened, or marked in other ways on
hardware. The following location labels might be shown in the location
code field (n represents a numerical or alphabetical identifier):

Utttt.mmm.sssssss Unit location

Pnn Planar location

Cnn Card location

Tnn Port location

Dnn Device location

Vnnn Virtual planar

Wnnnnnnnnnnnnnnnn Worldwide port name

Lnn Logical path location

606 IBM i: Performance and Query Optimization


Table 136. HARDWARE_RESOURCE_INFO table function

Column Name Data Type Description

LOCATION_CODE (continued) Following are the descriptions of the location labels:

Unit location Value of the unit enclosure


identifier composed of
uppercase alphabetic characters
and digits. This value will often
be composed of the machine
type (tttt), model (mmm) and
serial number (sssssss).

Planar location Decimal value of the planar


identifier within the unit.

Card location The decimal value of the position


of the card within the hardware
package. This can be followed
by additional card location labels
that would identify the decimal
value of additional card positions
of the resource on the card.

Port location The decimal value of the port


location within the resource.

Device location The decimal value of the position


of the device within the hardware
package.

Virtual planar The decimal value of the position


of the virtual planar resource
within the hardware package.

Worldwide port name The hexadecimal value of the


worldwide port name of the
resource within the hardware
package. This value is usually
present for fibre channel devices.
It will be blank for fibre channel
adapters. See the Retrieve
Resource Information (QRZRRSI)
API and key value 169 for fibre
channel adapters.

Logical path location The decimal value of the logical


path of the resource within the
hardware package. This can be
followed by additional logical
path location labels that would
identify the decimal value of
additional logical path data of
the resource on the hardware
package.

This column is available only if the system supports the location code
format and if the value applies for the resource Otherwise the null
value is returned.

IO_BUS_ADDRESS INTEGER The I/O bus address of the resource.


Contains the null value if the column does not apply to the resource.

ADAPTER_ADDRESS INTEGER The adapter address of the resource.


Contains the null value if the column does not apply to the resource.

DEVICE_ADDRESS INTEGER The device address of the resource.


Contains the null value if the column does not apply to the resource.

DEVICE_POSITION VARCHAR(5) The relative device position of the resource.


Contains the null value if the column does not apply to the resource.

CONTROLLER_ADDRESS INTEGER The controller address of the resource.


Contains the null value if the column does not apply to the resource.

Database performance and query optimization 607


Table 136. HARDWARE_RESOURCE_INFO table function (continued)

Column Name Data Type Description

SYSTEM_PROCESSOR_ CHAR(4) The processor feature code level of the system. A value is returned
FEATURE_CODE for this column only if the RESOURCE_KIND3 value of the hardware
resource indicates that the resource provides system information
(X'0000000000080000').
Contains the null value if the column does not apply to the resource.

PROCESSOR_FEATURE_CODE CHAR(4) The processor feature, which corresponds to the processor capacity of
the system.
Contains the null value if the column does not apply to the resource.

INTERACTIVE_FEATURE_CODE CHAR(4) The interactive feature of the system. This feature defines the portion
of the processor that can be used to perform interactive work.
Contains the null value if the column does not apply to the resource.

SHARED_SESSION_NUMBER INTEGER The shared session number of the resource.


Contains the null value if the column does not apply to the resource.

PORT_NUMBER INTEGER The port number of the resource.


Contains the null value if the column does not apply to the resource.

LAN_SPEED VARCHAR(12) The LAN speed for communications ports.

4M

16M

4M AND 16M

25M

34M

45M

100M

155M

10M AND 100M

10M TO 1G

1G

10G

1G AND 10G

25G

40G

50G

56G

100G

1G TO 100G

1G TO 25G

Contains the null value if the column does not apply to the resource.

LINK_AGGREGATION VARCHAR(3) Whether ports can be aggregated to compose an aggregate link.

NO Link aggregation is not supported.

YES Link aggregation is supported.

Contains the null value if the column does not apply to the resource.

DEFAULT_MAC_ADDRESS BINARY(6) The default MAC address of a LAN port.


Contains the null value if the column does not apply to the resource.

Example
• Return full information about tape resources.

608 IBM i: Performance and Query Optimization


SELECT * FROM TABLE (QSYS2.HARDWARE_RESOURCE_INFO(RESOURCE_CATEGORY => 'TAPE',
DETAILED_INFO => 'YES'));

HARDWARE_RESOURCE_INFO view
The HARDWARE_RESOURCE_INFO view returns information about configured hardware resources.
The information returned is similar to the detail available through the STRSST Hardware Service Manager
interface and from the Retrieve Hardware Resource List (QGYRHRL, QgyRtvHdwRscList) and Retrieve
Hardware Resource Information (QGYRHRI, QgyRtvHdwRscInfo) APIs.
Authorization: None required.
The following table describes the columns in the view. The system name is HW_INFO. The schema is
QSYS2.
Table 137. HARDWARE_RESOURCE_INFO view

Column Name System Column Name Data Type Description

ID ID INTEGER A generated unique identifier for this row in the result


set.

PARENT_ID PARENT_ID INTEGER The ID of the parent to this resource.

Nullable Contains the null value if this resource is not a child of


another resource.

RESOURCE_CATEGORY CATEGORY VARCHAR(11) The hardware resource category of the resource for
which information is returned.

ADAPTER Coupled system adapter


resources.

COMM Communication resources.

CRYPTO Cryptographic resources.

OPTICAL Optical resources.

PROCESSOR Processor resources.

STORAGE Storage device resources.

TAPE Tape resources.

WORKSTATION Local workstation resources.

RESOURCE_NAME RESOURCE VARCHAR(10) The name of the resource.

STATUS STATUS VARCHAR(12) Whether the resource is operational.

Nullable INOPERATIVE Resource is not operational.

NOT DETECTED Presence of resource could not


be detected.

OPERATIONAL Resource is operational.

Contains the null value if STATUS does not apply to


this resource or could not be determined.

Database performance and query optimization 609


Table 137. HARDWARE_RESOURCE_INFO view (continued)

Column Name System Column Name Data Type Description

EXTENDED_STATUS EXT_STATUS VARCHAR(14) The extended hardware status of the resource.

Nullable DEGRADED Resource is operational but


performance is degraded.

DISABLED Resource is currently


disabled.

ERROR Resource is operational but


errors have been detected.

FAILED Resource has failed.

INOPERATIVE Resource is not operational.

NO POWER Resource is powered off or no


power is being supplied to it.

NOT CONNECTED Resource is not connected.

NOT INSTALLED Resource is not installed.

OPERATIONAL Resource is operational.

SOFTWARE ERROR Resource is failed due to a


system software error.

Contains the null value if STATUS does not apply to


this resource or could not be determined.

DEVICE_TYPE DEV_TYPE VARCHAR(4) An identifier that represents the object type of


this resource. For self-configuring tape devices, this
Nullable represents the emulated device type number.
A value of *TAP indicates that a self-configuring
tape device is emulating a device type that contains
characters outside the range of 0 to 9 and A to Z.
Contains the null value if a value is not available.

DEVICE_MODEL DEV_MODEL VARCHAR(3) The model number of the resource. For self-
configuring tape devices, this represents the
Nullable emulated device model number.
Contains the null value if a value is not available.

ADAPTER_SYSTEM ADAPT_SYS VARCHAR(8) The system to which the coupled system adapter is
connected.
Nullable
Contains the null value if a value is not available.

LAN_ADAPTER_ADDRESS LAN_ADAPT VARCHAR(12) The network address of the LAN adapter resource.

Nullable Contains the null value if a value is not available.

LINE_TYPE LINE_TYPE VARCHAR(5) The line type of the LAN resource.

Nullable FDDI Fiber distributed data interface.

TOKEN Token ring.

Contains the null value if the resource has no line


type.

TEXT_DESCRIPTION TEXT VARCHAR(50) The description of the resource.

Nullable Contains the null value if there is no descriptive text.

MESSAGE_ID MESSAGE_ID CHAR(7) The message from which TEXT_DESCRIPTION is


obtained. This message is in the QCPFMSG message
Nullable file in *LIBL.
Contains the null value if there is no descriptive text.

RESOURCE_KIND KIND BINARY(24) The resource kind field consists of 24 bytes of


hexadecimal numbers. It can be divided into three
8-byte fields called Kind 1, Kind 2, and Kind 3. The
system uses Kind 1, Kind 2, and Kind 3 to categorize
the resource.

RESOURCE_KIND1 KIND1 BINARY(8) The value for Kind 1.

RESOURCE_KIND2 KIND2 BINARY(8) The value for Kind 2.

610 IBM i: Performance and Query Optimization


Table 137. HARDWARE_RESOURCE_INFO view

Column Name System Column Name Data Type Description

RESOURCE_KIND3 KIND3 BINARY(8) The value for Kind 3.

SERIAL_NUMBER SERIAL_NBR VARCHAR(15) The expanded unique number based on the


manufacturing sequence for the resource.

SERIAL_NUMBER_SHORT SHORT_SN VARCHAR(10) A unique number based on the manufacturing


sequence for the resource.

PART_NUMBER PART VARCHAR(12) A manufacturing identifier that represents similar


types of hardware.
Nullable
Contains the null value if the column does not apply
to the resource.

BUS_NUMBER BUS_NBR INTEGER A numerical representation of the path connection of


the system processor to the card.
Nullable
Contains the null value if the column does not apply
to the resource.

BOARD_NUMBER BOARD_NBR INTEGER A numerical representation of a section of the bus


into which the card is plugged.
Nullable
Contains the null value if the column does not apply
to the resource.

CARD_NUMBER CARD_NBR INTEGER A numerical representation of the location of the card


on the bus.
Nullable
Contains the null value if the column does not apply
to the resource.

CARD_POSITION CARD_POS VARCHAR(5) The physical location where the device or feature is
plugged into the bus.
Nullable
Contains the null value if the column does not apply
to the resource.

FRAME_ID FRAME VARCHAR(4) The identifier of a frame resource.

Nullable Contains the null value if the column does not apply
to the resource.

LOCATION_CODE LOC_CODE VARCHAR(79) The physical location of the hardware resource in the
system.
Nullable
The location code field is a sequence of 0 or more
location labels that when followed in order, lead to
the resource location. This is the place someone
could go to view, remove, or replace the piece of
hardware. Location labels are etched, silk screened,
or marked in other ways on hardware. The following
location labels might be shown in the location
code field (n represents a numerical or alphabetical
identifier):

Utttt.mmm.sssssss Unit location

Pnn Planar location

Cnn Card location

Tnn Port location

Dnn Device location

Vnnn Virtual planar

Wnnnnnnnnnnnnnnnn Worldwide port name

Lnn Logical path location

Database performance and query optimization 611


Table 137. HARDWARE_RESOURCE_INFO view

Column Name System Column Name Data Type Description

LOCATION_CODE (continued) Following are the descriptions of the location labels:

Unit location Value of the unit


enclosure identifier
composed of uppercase
alphabetic characters
and digits. This value
will often be composed
of the machine type
(tttt), model (mmm) and
serial number (sssssss).

Planar location Decimal value of the


planar identifier within
the unit.

Card location The decimal value of


the position of the card
within the hardware
package. This can be
followed by additional
card location labels
that would identify
the decimal value of
additional card positions
of the resource on the
card.

Port location The decimal value of the


port location within the
resource.

Device location The decimal value of the


position of the device
within the hardware
package.

Virtual planar The decimal value of the


position of the virtual
planar resource within
the hardware package.

Worldwide port name The hexadecimal value


of the worldwide port
name of the resource
within the hardware
package. This value
is usually present for
fibre channel devices. It
will be blank for fibre
channel adapters. See
the Retrieve Resource
Information (QRZRRSI)
API and key value
169 for fibre channel
adapters.

Logical path location The decimal value of


the logical path of
the resource within
the hardware package.
This can be followed
by additional logical
path location labels
that would identify
the decimal value of
additional logical path
data of the resource on
the hardware package.

This column is available only if the system supports


the location code format and if the value applies for
the resource Otherwise the null value is returned.

IO_BUS_ADDRESS IOBUS_ADDR INTEGER The I/O bus address of the resource.

Nullable Contains the null value if the column does not apply
to the resource.

612 IBM i: Performance and Query Optimization


Table 137. HARDWARE_RESOURCE_INFO view (continued)

Column Name System Column Name Data Type Description

ADAPTER_ADDRESS ADAPT_ADDR INTEGER The adapter address of the resource.

Nullable Contains the null value if the column does not apply
to the resource.

DEVICE_ADDRESS DEV_ADDR INTEGER The device address of the resource.

Nullable Contains the null value if the column does not apply
to the resource.

DEVICE_POSITION DEVICE_POS VARCHAR(5) The relative device position of the resource.

Nullable Contains the null value if the column does not apply
to the resource.

CONTROLLER_ADDRESS CON_ADDR INTEGER The controller address of the resource.

Nullable Contains the null value if the column does not apply
to the resource.

SYSTEM_PROCESSOR_ SYSPROC_FC CHAR(4) The processor feature code level of the system.
FEATURE_CODE A value is returned for this column only if
Nullable the RESOURCE_KIND3 value of the hardware
resource indicates that the resource provides system
information (X'0000000000080000').
Contains the null value if the column does not apply
to the resource.

PROCESSOR_FEATURE_CODE PROC_FC CHAR(4) The processor feature, which corresponds to the


processor capacity of the system.
Nullable
Contains the null value if the column does not apply
to the resource.

INTERACTIVE_FEATURE_CODE INTER_FC CHAR(4) The interactive feature of the system. This feature
defines the portion of the processor that can be used
Nullable to perform interactive work.
Contains the null value if the column does not apply
to the resource.

SHARED_SESSION_NUMBER SHARED_SES INTEGER The shared session number of the resource.

Nullable Contains the null value if the column does not apply
to the resource.

PORT_NUMBER PORT INTEGER The port number of the resource.

Nullable Contains the null value if the column does not apply
to the resource.

Database performance and query optimization 613


Table 137. HARDWARE_RESOURCE_INFO view (continued)

Column Name System Column Name Data Type Description

LAN_SPEED LAN_SPEED VARCHAR(12) The LAN speed for communications ports.

Nullable 4M

16M

4M AND 16M

25M

34M

45M

100M

155M

10M AND 100M

10M TO 1G

1G

10G

1G AND 10G

25G

40G

50G

56G

100G

1G TO 100G

1G TO 25G

Contains the null value if the column does not apply


to the resource.

LINK_AGGREGATION LINK_AGGR VARCHAR(3) Whether ports can be aggregated to compose an


aggregate link.
Nullable
NO Link aggregation is not supported.

YES Link aggregation is supported.

Contains the null value if the column does not apply


to the resource.

DEFAULT_MAC_ADDRESS MAC_ADDR BINARY(6) The default MAC address of a LAN port.


Nullable Contains the null value if the column does not apply
to the resource.

Examples
• List all resources that are not operational.

SELECT RESOURCE_NAME, STATUS, EXTENDED_STATUS FROM QSYS2.HARDWARE_RESOURCE_INFO


WHERE STATUS <> 'OPERATIONAL';

• Return a list of all resources and their children. For each parent device (those with a PARENT_ID value
that is null), it recursively finds all the children that are under the parent. In addition to some basic
resource information and the ID values for the parent and child, the query returns the nesting depth of
the each row and a list of all the device numbers that form the path to that row.

SELECT TEXT_DESCRIPTION, RESOURCE_CATEGORY, RESOURCE_NAME, ID, PARENT_ID AS PART_OF,


LEVEL, SYS_CONNECT_BY_PATH (VARCHAR(ID), ' ') AS RESOURCE_PATH
FROM QSYS2.HARDWARE_RESOURCE_INFO
START WITH ID IN (SELECT ID FROM QSYS2.HARDWARE_RESOURCE_INFO WHERE PARENT_ID IS NULL)
CONNECT BY PRIOR ID = PARENT_ID;

614 IBM i: Performance and Query Optimization


IFS Services
These services provide information about the integrated file system.

COMPARE_IFS table function


The COMPARE_IFS table function returns differences between the specified integrated file system (IFS)
objects. This can be a single object or a subtree of objects starting from a specified directory.
Either a name compare or a full attribute compare can be requested. When comparing attributes, one row
is returned for each attribute that is different between a pair of objects. The attributes are a subset of
the values returned by the QSYS2.IFS_OBJECT_STATISTICS and QSYS2.IFS_OBJECT_PRIVILEGES table
functions.
If no differences are found for any objects, no rows are returned.
The integrated file system supports many file systems. Only those objects in the root (/) and QOpenSys
file systems can be compared. Other file systems are not supported. The specified start-path-name1 and
start-path-name2 must be in a supported file system or an error will occur.
Independent auxiliary storage pool (IASP) objects are supported. start-path-name1 and start-path-name2
can be within an IASP.
Authorization: The caller must have:
• For each directory included in the path name used to start the compare, *X
• For each directory processed recursively, *RX and *OBJMGT
• For each object compared, *OBJMGT
The caller must have *ALLOBJ or *AUDIT special authority to compare the object auditing attributes for
objects and directories. If the caller does not have this authority, a difference in these values will not be
reported.
Any object for which the caller does not have sufficient authority will be treated as though it does not
exist.

COMPARE_IFS ( start-path-name1 ,
START_PATH_NAME1 =>

start-path-name2
START_PATH_NAME2 =>

, rdb2
RDB2 =>

, subtree-directories
SUBTREE_DIRECTORIES =>

, object-type-list
OBJECT_TYPE_LIST =>

)
, compare-attributes
COMPARE_ATTRIBUTES =>

The schema is QSYS2.

Database performance and query optimization 615


start-path- An expression that returns a path name for the first object of the comparison. A relative
name1 path name is relative to the current directory. If an absolute path name is not specified,
the current working directory is used in combination with the relative path name to
resolve to the object. The object must exist on the current server.
If start-path-name1 identifies an object, the single object is compared with the object
provided by start-path-name2. If start-path-name1 identifies a directory, the directory
and all objects included in the object-type-list within the directory are compared with
the directory provided by start-path-name2. When comparing directories, the subtree-
directories parameter determines whether the compare will process subdirectories.
start-path- An expression that returns a path name for the second object of the comparison. A
name2 relative path name is relative to the current directory. If an absolute path name is not
specified, the current working directory on rdb2 is used in combination with the relative
path name to resolve to the object. The object must exist on the server implicitly or
explicitly identified by rdb2.
rdb2 A character or graphic string expression that identifies the relational database where
start-path-name2 exists.
If this parameter is omitted, start-path-name2 must exist on the current server.
subtree- An expression that indicates whether all subdirectories are recursively compared. This
directories parameter only applies when comparing directories. Otherwise, the value is ignored.

NO The objects in the directory identified by start-path-name1 are compared to the


objects in the directory identified by start-path-name2.
YES All objects in all subdirectories for the directory identified by start-path-name1 are
compared to the corresponding objects in start-path-name2. This is the default.

object-type- A list of one or more object types to be included in the compare. One or more blanks
list separate multiple values. The default is *ALL, indicating all object types are compared.
Supported values are all of the root (/) and QOpenSys file system object types (*CHRSF,
*DIR, *FIFO, *SOCKET, *STMF, *SYMLNK) and the following special values:

*ALL Compare all root (/) and QOpenSys file system object types. These are
*CHRSF, *DIR, *FIFO, *SOCKET, *STMF, and *SYMLNK.
*ALLSAV Compare all root (/) and QOpenSys file system object types which can be
saved using the Save (SAV) command. These are *CHRSF, *DIR, *FIFO,
*STMF, and *SYMLNK.

compare- A string expression that indicates which attributes are compared for an object.
attributes
NAMES Only the object names are compared. A row is returned for any name that
is not found in both directories. This option is only allowed when comparing
directories. This is the default.
YES The attributes are compared for an object. A row is returned for each difference
found.

The attributes compared for an object vary based upon the object type. Not all attributes
are eligible to be compared.

The result of the function is a table containing rows with the format shown in the following table. All
columns are nullable.
Table 138. COMPARE_IFS table function

Column Name Data Type Description

PATH_NAME1 DBCLOB(16M) The full path name of the first object for the compare.

CCSID 1200

616 IBM i: Performance and Query Optimization


Table 138. COMPARE_IFS table function (continued)

Column Name Data Type Description

PATH_NAME2 DBCLOB(16M) The full path name of the second object for the compare.

CCSID 1200

ATTRIBUTE_NAME VARGRAPHIC(512) The name of an object attribute that is not identical.

CCSID 1200

VALUE1 VARGRAPHIC(2048) The attribute value for the first object.

CCSID 1200

VALUE2 VARGRAPHIC(2048) The attribute value for the second object.

CCSID 1200

Examples
• Compare the attributes for all objects in two subtrees. Do not look within any subdirectories.

SELECT * FROM TABLE(QSYS2.COMPARE_IFS(


START_PATH_NAME1 => '/usr',
START_PATH_NAME2 => '/usrbackup',
SUBTREE_DIRECTORIES => 'NO',
COMPARE_ATTRIBUTES => 'YES'
));

• Compare the names for all objects in two subtrees. Compare recursively through the entire set of
subdirectories.

SELECT * FROM TABLE(QSYS2.COMPARE_IFS(


START_PATH_NAME1 => '/usr/files.dir',
START_PATH_NAME2 => '/usrbackup/files.dir',
SUBTREE_DIRECTORIES => 'YES',
COMPARE_ATTRIBUTES => 'NAMES'
));

• Compare the attributes for all stream file objects recursively.

SELECT * FROM TABLE(QSYS2.COMPARE_IFS(


START_PATH_NAME1 => '/usr/files.dir',
START_PATH_NAME2 => '/usrbackup/files.dir',
OBJECT_TYPE_LIST => '*STMF',
SUBTREE_DIRECTORIES => 'YES',
COMPARE_ATTRIBUTES => 'YES'
));

IFS_JOB_INFO table function


The IFS_JOB_INFO table function returns a table that contains information about integrated file system
references for a job.
This information is similar to what is returned by the Retrieve Referenced Objects (QP0LRRO) API.
The list of objects returned may be incomplete for objects residing in file systems other than the root (/),
QOpenSys, and user-defined file systems. Objects in some of the other file systems can be locked with
interfaces that do not use the integrated file system. Therefore, objects referenced by a job will only have
references that were obtained as part of an integrated file system operation, or an operation that causes
an integrated file system operation to occur.
Authorization: The caller must be running with the same user profile as the job being retrieved or have
*JOBCTL special authority.

Database performance and query optimization 617


IFS_JOB_INFO ( job-name
JOB_NAME =>

)
, ignore-errors
IGNORE_ERRORS =>

job-name An expression that returns the qualified job name whose reference information is to be
returned. Can contain the following special value:

* Return information for the current job.

ignore-errors A character or graphic string expression that identifies what to do when an error is
encountered.

NO An error is returned.

YES A warning is returned.


No row is returned when an error is encountered. This is the default.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 139. IFS_JOB_INFO table function

Column Name Data Type Description

PATH_NAME DBCLOB(16M) CCSID The path name of an integrated file system object that is referenced by the
1200 job.
Contains the null value if the object is not linked to a path. This can occur
in the root (/) file system, the QOpenSys file system, or a user-defined file
system. Can also contain the null value if the object is in a remote file
system or the optical file system (QOPT).

FILE_SYSTEM_TYPE VARCHAR(15) The file system for the object.

NFS The Network File System (NFS).

QDLS The Document Library Services (QDLS) file


system.

QFILSVR400 The QFileSvr.400 file system.

QNTC The Windows NT® Server file system.

QOPENSYS The QOpenSys file system.

QOPT The optical file system (QOPT).

QSYS The QSYS.LIB file system.

QSYSIASP An independent ASP QSYS.LIB file system.

ROOT The root (/) file system

UDFS A user-defined file system.

UDFS MANAGEMENT A file system that manages the block special files
(*BLKSF) for the user-defined file systems.

FILE_IDENTIFIER_NUMBER BIGINT The file identifier number of the object. This number uniquely identifies the
object with a file system.
The file identifier number, generation identifier, and file system identifier
used together uniquely identify the object on the system.

GENERATION_IDENTIFIER BIGINT The generation identifier associated with the object.


The file identifier number, generation identifier, and file system identifier
used together uniquely identify the object on the system.

618 IBM i: Performance and Query Optimization


Table 139. IFS_JOB_INFO table function (continued)

Column Name Data Type Description

FILE_SYSTEM_IDENTIFIER BIGINT The file system ID to which the object belongs. This number uniquely
identifies the file system to which the object belongs.
The file identifier number, generation identifier, and file system identifier
used together uniquely identify the object on the system.

FILE_IDENTIFIER BINARY(16) An identifier associated with the referred to object.

REFERENCE_COUNT INTEGER Current number of references on the object for the specified job.

RO_SHARE_R_COUNT INTEGER Number of read only accesses for the job where the sharing mode allows
sharing with read and execute access intents only.

RO_SHARE_W_COUNT INTEGER Number of read only accesses for the job where the sharing mode allows
sharing with write access intents only.

RO_SHARE_RW_COUNT INTEGER Number of read only accesses for the job where the sharing mode allows
sharing with read, execute, and write access intents.

RO_SHARE_NONE_COUNT INTEGER Number of read only accesses for the job where the sharing mode allows
sharing with no other access intents.

WO_SHARE_R_COUNT INTEGER Number of write only accesses for the job where the sharing mode allows
sharing with read and execute access intents only.

WO_SHARE_W_COUNT INTEGER Number of write only accesses for the job where the sharing mode allows
sharing with write access intents only.

WO_SHARE_RW_COUNT INTEGER Number of write only accesses for the job where the sharing mode allows
sharing with read, execute, and write access intents.

WO_SHARE_NONE_COUNT INTEGER Number of write only accesses for the job where the sharing mode allows
sharing with no other access intents.

RW_SHARE_R_COUNT INTEGER Number of read and write accesses for the job where the sharing mode
allows sharing with read and execute access intents only.

RW_SHARE_W_COUNT INTEGER Number of read and write accesses for the job where the sharing mode
allows sharing with write access intents only.

RW_SHARE_RW_COUNT INTEGER Number of read and write accesses for the job where the sharing mode
allows sharing with read, execute, and write access intents.

RW_SHARE_NONE_COUNT INTEGER Number of read and write accesses for the job where the sharing mode
allows sharing with no other access intents.

XO_SHARE_R_COUNT INTEGER Number of execute only accesses for the job where the sharing mode allows
sharing with read and execute access intents only.

XO_SHARE_W_COUNT INTEGER Number of execute only accesses for the job where the sharing mode allows
sharing with write access intents only.

XO_SHARE_RW_COUNT INTEGER Number of execute only accesses for the job where the sharing mode allows
sharing with read, execute, and write access intents.

XO_SHARE_NONE_COUNT INTEGER Number of execute only accesses for the job where the sharing mode allows
sharing with no other access intents.

XR_SHARE_R_COUNT INTEGER Number of execute and read accesses for the job where the sharing mode
allows sharing with read and execute access intents only.

XR_SHARE_W_COUNT INTEGER Number of execute and read accesses for the job where the sharing mode
allows sharing with write access intents only.

XR_SHARE_RW_COUNT INTEGER Number of execute and read accesses for the job where the sharing mode
allows sharing with read, execute, and write access intents.

XR_SHARE_NONE_COUNT INTEGER Number of execute and read accesses for the job where the sharing mode
allows sharing with no other access intents.

CURRENT_DIRECTORY VARCHAR(3) The object is a directory that is being used as the current directory of the
job.

NO The object is not a directory that is being used as the current


directory of the job.

YES The object is the current directory of the job.

Database performance and query optimization 619


Table 139. IFS_JOB_INFO table function (continued)

Column Name Data Type Description

ROOT_DIRECTORY VARCHAR(3) The object is a directory that is being used as the root directory of the job.

NO The object is not a directory that is being used as the root directory
of the job.

YES The object is the root directory of the job.

ATTRIBUTE_LOCK VARCHAR(3) Indicates whether attribute changes are prevented.

NO Attribute changes are not prevented.

YES Attribute changes are prevented.

SAVE_LOCK VARCHAR(3) Indicates whether the object is being referenced by an object save
operation.

NO Object is not being referenced by an object save operation.

YES Object is being referenced by an object save operation.

INTERNAL_SAVE_LOCK VARCHAR(3) Indicates whether the object is being referenced internally during a save
operation on a different object.

NO The object is not being referenced internally during a save operation


on a different object.

YES The object is being referenced internally during a save operation on


a different object.

LINK_CHANGES_LOCK VARCHAR(3) Indicates whether changes to links in the directory are prevented.

NO Changes to links in the directory are not prevented.

YES Changes to links in the directory are prevented.

CHECKED_OUT VARCHAR(3) Indicates whether the object is currently checked out.

NO The object is not checked out.

YES The object is checked out.

CHECKED_OUT_USER_NAME VARCHAR(10) The name of the user who has the object checked out.
Contains the null value if CHECKED_OUT is NO.

FILE_SERVER_REFERENCE VARCHAR(3) The File Server is holding a generic reference on the object on behalf of a
client.

NO The File Server is not holding a generic reference on the object on


behalf of a client.

YES The File Server is holding a generic reference on the object on


behalf of a client.

FILE_SERVER_WORKING_DIRECTORY VARCHAR(3) The object is a directory, and the File Server is holding a working directory
reference on it on behalf of a client.

NO The object is not a directory or the File Server is not holding a


working directory reference on it on behalf of a client.

YES The object is a directory, and the File Server is holding a working
directory reference on it on behalf of a client.

NFS_SERVER_REFERENCE VARCHAR(3) The Network File System (NFS) Version 4 server job is holding a generic
reference on the object on behalf of a client.

NO The NFS server job is not holding a generic reference on the object
on behalf of a client.

YES The NFS server job is holding a generic reference on the object on
behalf of a client.

Example
• List all the integrated file system references for the current job.

620 IBM i: Performance and Query Optimization


SELECT * FROM TABLE(QSYS2.IFS_JOB_INFO(JOB_NAME => '*'));

IFS_OBJECT_LOCK_INFO table function


The IFS_OBJECT_LOCK_INFO table function returns a result table that contains a row for each job that is
known to be holding a reference, or lock, on the object.
This information is similar to what is returned by the Retrieve Object References (QP0LROR) API.
The list of object usages may be incomplete for objects residing in file systems other than the root (/),
QOpenSys, and user-defined file systems. Objects in some of the other file systems can be locked with
interfaces that do not use the integrated file system. Therefore, rows are only returned for references that
were obtained as part of an integrated file system operation, or an operation that cause the integrated file
system operation to occur.
Authorization: The caller must have:
• Execute (*X) data authority to each directory preceding the object whose references are to be obtained,
and
• Read (*R) data authority to the object whose references are to be obtained.

IFS_OBJECT_LOCK_INFO ( path-name
PATH_NAME =>

)
, ignore-errors
IGNORE_ERRORS =>

path- An expression that defines the path name to the object whose reference information is to
name be returned. If the last element of the path is a symbolic link, the reference information will
be for the symbolic link itself. If an absolute path name is not specified, the current working
directory is used in combination with the relative path name to resolve to the object.
ignore- A character or graphic string expression that identifies what to do when an error is
errors encountered.

NO An error is returned.

YES A warning is returned.


No row is returned when an error is encountered. This is the default.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 140. IFS_OBJECT_LOCK_INFO table function

Column Name Data Type Description

PATH_NAME DBCLOB(16M) CCSID The full path name of the object.


1200

JOB_NAME VARCHAR(28) The qualified job name holding the reference.

RO_COUNT INTEGER Total number of read only access references for this job.

WO_COUNT INTEGER Total number of write only access references for this job.

RW_COUNT INTEGER Total number of read and write access references for this job.

XO_COUNT INTEGER Total number of execute only access references for this job.

SHARE_R_COUNT INTEGER Total number of references for this job where the sharing mode allows
sharing with read and execute access intents only.

Database performance and query optimization 621


Table 140. IFS_OBJECT_LOCK_INFO table function (continued)

Column Name Data Type Description

SHARE_W_COUNT INTEGER Total number of references for this job where the sharing mode allows
sharing with write access intents only.

SHARE_RW_COUNT INTEGER Total number of references for this job where the sharing mode allows
sharing with read, execute, and write access intents.

SHARE_NONE_COUNT INTEGER Total number of references for this job where the sharing mode allows
sharing with no other access intents.

ATTRIBUTE_LOCK VARCHAR(3) Indicates whether attribute changes are prevented for this job.

NO Attribute changes are not prevented.

YES Attribute changes are prevented.

SAVE_LOCK VARCHAR(3) Indicates whether the object is being referenced by an object save
operation by this job.

NO Object is not being referenced by an object save operation.

YES Object is being referenced by an object save operation.

INTERNAL_SAVE_LOCK VARCHAR(3) Indicates whether the object is being referenced internally during a save
operation on a different object by this job.

NO The object is not being referenced internally during a save operation


on a different object.

YES The object is being referenced internally during a save operation on


a different object.

LINK_CHANGES_LOCK VARCHAR(3) Indicates whether changes to links in the directory are prevented for this
job.

NO Changes to links in the directory are not prevented.

YES Changes to links in the directory are prevented.

CHECKED_OUT VARCHAR(3) Indicates whether the object is currently checked out by this job.

NO The object is not checked out.

YES The object is checked out.

CHECKED_OUT_USER_NAME VARCHAR(10) The name of the user who has the object checked out.
Contains the null value if CHECKED_OUT is NO.

RO_SHARE_R_COUNT INTEGER Number of read only accesses for the job where the sharing mode allows
sharing with read and execute access intents only.

RO_SHARE_W_COUNT INTEGER Number of read only accesses for the job where the sharing mode allows
sharing with write access intents only.

RO_SHARE_RW_COUNT INTEGER Number of read only accesses for the job where the sharing mode allows
sharing with read, execute, and write access intents.

RO_SHARE_NONE_COUNT INTEGER Number of read only accesses for the job where the sharing mode allows
sharing with no other access intents.

WO_SHARE_R_COUNT INTEGER Number of write only accesses for the job where the sharing mode allows
sharing with read and execute access intents only.

WO_SHARE_W_COUNT INTEGER Number of write only accesses for the job where the sharing mode allows
sharing with write access intents only.

WO_SHARE_RW_COUNT INTEGER Number of write only accesses for the job where the sharing mode allows
sharing with read, execute, and write access intents.

WO_SHARE_NONE_COUNT INTEGER Number of write only accesses for the job where the sharing mode allows
sharing with no other access intents.

RW_SHARE_R_COUNT INTEGER Number of read and write accesses for the job where the sharing mode
allows sharing with read and execute access intents only.

RW_SHARE_W_COUNT INTEGER Number of read and write accesses for the job where the sharing mode
allows sharing with write access intents only.

RW_SHARE_RW_COUNT INTEGER Number of read and write accesses for the job where the sharing mode
allows sharing with read, execute, and write access intents.

622 IBM i: Performance and Query Optimization


Table 140. IFS_OBJECT_LOCK_INFO table function (continued)

Column Name Data Type Description

RW_SHARE_NONE_COUNT INTEGER Number of read and write accesses for the job where the sharing mode
allows sharing with no other access intents.

XO_SHARE_R_COUNT INTEGER Number of execute only accesses for the job where the sharing mode allows
sharing with read and execute access intents only.

XO_SHARE_W_COUNT INTEGER Number of execute only accesses for the job where the sharing mode allows
sharing with write access intents only.

XO_SHARE_RW_COUNT INTEGER Number of execute only accesses for the job where the sharing mode allows
sharing with read, execute, and write access intents.

XO_SHARE_NONE_COUNT INTEGER Number of execute only accesses for the job where the sharing mode allows
sharing with no other access intents.

XR_SHARE_R_COUNT INTEGER Number of execute and read accesses for the job where the sharing mode
allows sharing with read and execute access intents only.

XR_SHARE_W_COUNT INTEGER Number of execute and read accesses for the job where the sharing mode
allows sharing with write access intents only.

XR_SHARE_RW_COUNT INTEGER Number of execute and read accesses for the job where the sharing mode
allows sharing with read, execute, and write access intents.

XR_SHARE_NONE_COUNT INTEGER Number of execute and read accesses for the job where the sharing mode
allows sharing with no other access intents.

CURRENT_DIRECTORY VARCHAR(3) Indicates whether the object is a directory that is being used as the current
directory of the job.

NO The object is not a directory that is being used as the current


directory of the job.

YES The object is a directory that is being used as the current directory
of the job.

ROOT_DIRECTORY VARCHAR(3) Indicates whether the object is a directory that is being used as the root
directory of the job.

NO The object is not a directory that is being used as the root directory
of the job.

YES The object is a directory that is being used as the root directory of
the job.

FILE_SERVER_REFERENCE VARCHAR(3) Indicates whether the File Server is holding a generic reference on the
object on behalf of a client for this job.

NO The File Server is not holding a generic reference on the object on


behalf of a client.

YES The File Server is holding a generic reference on the object on


behalf of a client.

FILE_SERVER_WORKING_DIRECTORY VARCHAR(3) Indicates whether the object is a directory, and the File Server is holding a
working directory reference on it on behalf of a client for this job.

NO The object is not a directory or the File Server is not holding a


working directory reference on it on behalf of a client.

YES The object is a directory, and the File Server is holding a working
directory reference on it on behalf of a client.

NFS_SERVER_REFERENCE VARCHAR(3) Indicates whether the Network File System (NFS) Version 4 server job is
holding a generic reference on the object on behalf of a client for this job.

NO The NFS server job is not holding a generic reference on the object
on behalf of a client.

YES The NFS server job is holding a generic reference on the object on
behalf of a client.

Database performance and query optimization 623


Table 140. IFS_OBJECT_LOCK_INFO table function (continued)

Column Name Data Type Description

NETSERVER_SESSION CLOB(1M) This column contains a list of NetServer sessions, with each entry formatted
as follows:
1. 20 characters containing the session ID number
2. 10 character user name
3. 15 character workstation name
4. 45 character workstation address
5. 1 semicolon (;)
Contains the null value if there are no NetServer sessions.

Example
• List all the jobs that have a lock on /usr/test1

SELECT * FROM TABLE(QSYS2.IFS_OBJECT_LOCK_INFO(PATH_NAME => '/usr/test1'))

IFS_OBJECT_PRIVILEGES table function


The IFS_OBJECT_PRIVILEGES table function returns a row for every user authorized to the object
identified by the path name, along with their associated object and data authorities.
This information is similar to the information available through the Display Authority (DSPAUT) CL
command and the Qp0lGetAttr()--Get Attributes API.
Authorization: The caller must have:
• For objects not in the QSYS.LIB file system:
– For each directory included in the path name prior to the object name, *X
– For the object, *OBJMGT
• For objects in the QSYS.LIB file system:
– For each directory included in the path name prior to the object name, *X
– For a *MBR object, *RX and *OBJMGT
– For all other object types, *OBJMGT

IFS_OBJECT_PRIVILEGES ( path-name
PATH_NAME =>

)
, ignore-errors
IGNORE_ERRORS =>

path- An expression that returns the path name identifying the object. A relative path name is
name relative to the current directory. If an absolute path name is not specified, the current
working directory is used in combination with the relative path name to resolve to the
object. If the last element of the path is a symbolic link, the privilege information will be for
the symbolic link itself.
ignore- A character or graphic string expression that identifies what to do when an error is
errors encountered.

NO An error is returned.

YES A warning is returned.


No row is returned when an error is encountered. This is the default.

624 IBM i: Performance and Query Optimization


The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 141. IFS_OBJECT_PRIVILEGES table function

Column Name Data Type Description

PATH_NAME DBCLOB(16M) CCSID The full path name of the object.


1200

OBJECT_TYPE VARCHAR(8) The type of the object.

OWNER VARCHAR(10) The user profile that owns the object.


Contains the null value if no owner is available.

PRIMARY_GROUP VARCHAR(10) The name of the user profile that is the primary group of the object. Can
contain the following special value:

*NOUSRPRF This special value is used by the Network File System to


indicate that there is no user profile on the local server on
the IBM i with a group ID (GID) matching the GID of the
remote object.

Contains the null value if the object has no primary group.

AUTHORIZATION_LIST VARCHAR(10) The name of the authorization list if the object is secured by an
authorization list.
Contains the null value if the object is not secured by an authorization list.

AUTHORIZATION_NAME VARCHAR(10) User profile name for this row. Can contain the following special values:

*NOUSRPRF The authorities of either the owner or the primary group


of the object for which the profile name could not be
determined. This value is used by the Network File System
only. It indicates that the user ID (UID) or the group ID
(GID) for the remote object does not match any profile on
the local server on the IBM i with that UID or GID.

*PUBLIC This row contains the public authority for the object.

DATA_AUTHORITY VARCHAR(12) The operation, use, or access that AUTHORIZATION_NAME has to the
object. Contains one of the following special values:

*AUTL The public authority specified in the authorization list


used by this object is used.

*EXCLUDE All operations on the object are prohibited.

*NONE The user does not have any data authorities.

*R Allows access to the object attributes.

*RW Allows access to the object attributes and allows the


object to be changed. The user cannot use the object.

*RWX Allows all operations on the object except those that are
limited to the owner or controlled by the object rights.

*RX Allows access to the object attributes and use of the


object. The user cannot change the object.

*W Allows the object to be changed.

*WX Allows use of the object and allows the object to be


changed. The user cannot access the object attributes.

*X Allows the use of the object.

USER DEFINED The specific data authorities do not match any of the
predefined authority levels.

OBJECT_OPERATIONAL VARCHAR(3) Indicates the object operational authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_MANAGEMENT VARCHAR(3) The object management authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

Database performance and query optimization 625


Table 141. IFS_OBJECT_PRIVILEGES table function (continued)

Column Name Data Type Description

OBJECT_EXISTENCE VARCHAR(3) The object existence authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_ALTER VARCHAR(3) The object alter authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_REFERENCE VARCHAR(3) The object reference authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_READ VARCHAR(3) The data read authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_ADD VARCHAR(3) The data add authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_UPDATE VARCHAR(3) The data update authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_DELETE VARCHAR(3) The data delete authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_EXECUTE VARCHAR(3) The data execute authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

Example
• List all the authorities for all objects in the /usr directory.

WITH OBJS AS (SELECT PATH_NAME


FROM TABLE (QSYS2.IFS_OBJECT_STATISTICS(START_PATH_NAME => '/usr')))
SELECT * FROM OBJS, TABLE(QSYS2.IFS_OBJECT_PRIVILEGES(PATH_NAME));

IFS_OBJECT_REFERENCES_INFO table function


The IFS_OBJECT_REFERENCES_INFO table function returns a single row result table that contains
information about integrated file system references on an object.
This information is similar to what is returned by the Retrieve Object References (QP0LROR) API. The
information may not be complete for objects residing in file systems other than the root (/), QOpenSys,
and user-defined file systems.
Authorization: The caller must have:
• Execute (*X) data authority to each directory preceding the object whose references are to be obtained,
and
• Read (*R) data authority to the object whose references are to be obtained.

626 IBM i: Performance and Query Optimization


IFS_OBJECT_REFERENCES_INFO ( path-name
PATH_NAME =>

, detailed-info
DETAILED_INFO =>

)
, ignore-errors
IGNORE_ERRORS =>

path-name An expression that defines the path name to the object whose reference information is to
be returned. If the last element of the path is a symbolic link, the reference information
will be for the symbolic link itself. If an absolute path name is not specified, the current
working directory is used in combination with the relative path name to resolve to the
object.
detailed- A character or graphic string expression that indicates the type of information to be
info returned.

NO Only basic information is returned. Values for columns through the


CHECKED_OUT_USER_NAME are returned; NULL is returned for the remaining
columns. This is the default.
YES Values are returned for all columns.

ignore- A character or graphic string expression that identifies what to do when an error is
errors encountered.

NO An error is returned.

YES A warning is returned.


No row is returned when an error is encountered. This is the default.

The result of the function is a table containing a single row with the format shown in the following table.
All the columns are nullable.
Table 142. IFS_OBJECT_REFERENCES_INFO table function

Column Name Data Type Description

PATH_NAME DBCLOB(16M) CCSID The full path name of the object.


1200

REFERENCE_COUNT INTEGER Current number of references on the object. This may be 0 even though
IN_USE has a value of YES.

IN_USE VARCHAR(3) Whether the object is currently in use.

NO The object is not in use and all of the reference type fields are 0.

YES The object is in use. At least one of the reference type


fields is greater than 0. This condition may occur even if
REFERENCE_COUNT is 0.

RO_COUNT INTEGER Total number of read only access references.

WO_COUNT INTEGER Total number of write only access references.

RW_COUNT INTEGER Total number of read and write access references.

XO_COUNT INTEGER Total number of execute only access references.

SHARE_R_COUNT INTEGER Total number of references where the sharing mode allows sharing with
read and execute access intents only.

Database performance and query optimization 627


Table 142. IFS_OBJECT_REFERENCES_INFO table function (continued)

Column Name Data Type Description

SHARE_W_COUNT INTEGER Total number of references where the sharing mode allows sharing with
write access intents only.

SHARE_RW_COUNT INTEGER Total number of references where the sharing mode allows sharing with
read, execute, and write access intents.

SHARE_NONE_COUNT INTEGER Total number of references where the sharing mode allows sharing with no
other access intents.

ATTRIBUTE_LOCK VARCHAR(3) Indicates whether attribute changes are prevented.

NO Attribute changes are not prevented.

YES Attribute changes are prevented.

SAVE_LOCK VARCHAR(3) Indicates whether the object is being referenced by an object save
operation.

NO Object is not being referenced by an object save operation.

YES Object is being referenced by an object save operation.

INTERNAL_SAVE_LOCK VARCHAR(3) Indicates whether the object is being referenced internally during a save
operation on a different object.

NO The object is not being referenced internally during a save operation


on a different object.

YES The object is being referenced internally during a save operation on


a different object.

LINK_CHANGES_LOCK VARCHAR(3) Indicates whether changes to links in the directory are prevented.

NO Changes to links in the directory are not prevented.

YES Changes to links in the directory are prevented.

CHECKED_OUT VARCHAR(3) Indicates whether the object is currently checked out.

NO The object is not checked out.

YES The object is checked out.

CHECKED_OUT_USER_NAME VARCHAR(10) The name of the user who has the object checked out.
Contains the null value if CHECKED_OUT is NO.

Values are returned for the following columns when the DETAILED_INFO parameter is YES. They will contain the null value if DETAILED_INFO
is NO.

RO_SHARE_R_COUNT INTEGER Total number of read only access references. The sharing mode allows
sharing with read and execute access intents only.

RO_SHARE_W_COUNT INTEGER Total number of read only access references. The sharing mode allows
sharing with write access intents only.

RO_SHARE_RW_COUNT INTEGER Total number of read only access references. The sharing mode allows
sharing with read, execute, and write access intents.

RO_SHARE_NONE_COUNT INTEGER Total number of read only access references. The sharing mode allows
sharing with no other access intents.

WO_SHARE_R_COUNT INTEGER Total number of write only access references. The sharing mode allows
sharing with read and execute access intents only.

WO_SHARE_W_COUNT INTEGER Total number of write only access references. The sharing mode allows
sharing with write access intents only.

WO_SHARE_RW_COUNT INTEGER Total number of write only access references. The sharing mode allows
sharing with read, execute, and write access intents.

WO_SHARE_NONE_COUNT INTEGER Total number of write only access references. The sharing mode allows
sharing with no other access intents.

RW_SHARE_R_COUNT INTEGER Total number of read and write access references. The sharing mode allows
sharing with read and execute access intents only.

RW_SHARE_W_COUNT INTEGER Total number of read and write access references. The sharing mode allows
sharing with write access intents only.

628 IBM i: Performance and Query Optimization


Table 142. IFS_OBJECT_REFERENCES_INFO table function (continued)

Column Name Data Type Description

RW_SHARE_RW_COUNT INTEGER Total number of read and write access references. The sharing mode allows
sharing with read, execute, and write access intents.

RW_SHARE_NONE_COUNT INTEGER Total number of read and write access references. The sharing mode allows
sharing with no other access intents.

XO_SHARE_R_COUNT INTEGER Total number of execute only access references. The sharing mode allows
sharing with read and execute access intents only.

XO_SHARE_W_COUNT INTEGER Total number of execute only access references. The sharing mode allows
sharing with write access intents only.

XO_SHARE_RW_COUNT INTEGER Total number of execute only access references. The sharing mode allows
sharing with read, execute, and write access intents.

XO_SHARE_NONE_COUNT INTEGER Total number of execute only access references. The sharing mode allows
sharing with no other access intents.

XR_SHARE_R_COUNT INTEGER Total number of execute and read access references. The sharing mode
allows sharing with read and execute access intents only.

XR_SHARE_W_COUNT INTEGER Total number of execute and read access references. The sharing mode
allows sharing with write access intents only.

XR_SHARE_RW_COUNT INTEGER Total number of execute and read access references. The sharing mode
allows sharing with read, execute, and write access intents.

XR_SHARE_NONE_COUNT INTEGER Total number of execute and read access references. The sharing mode
allows sharing with no other access intents.

CURRENT_DIRECTORY_COUNT INTEGER Total number of jobs where the object is a directory that is being used as the
current directory of the job.

ROOT_DIRECTORY_COUNT INTEGER Total number of jobs where the object is a directory that is being used as the
root directory of the job.

FILE_SERVER_REFERENCE_COUNT INTEGER Total number of jobs where the File Server is holding a generic reference on
the object on behalf of a client.

FILE_SERVER_WORKING_DIRECTORY_ INTEGER Total number of jobs where the object is a directory, and the File Server is
COUNT holding a working directory reference on it on behalf of a client.

NFS_SERVER_REFERENCE_COUNT INTEGER Total number of jobs where the Network File System (NFS) Version 4 server
job is holding a generic reference on the object on behalf of a client.

Example
• Determine how /usr/test is currently being used.

SELECT * FROM TABLE (QSYS2.IFS_OBJECT_REFERENCES_INFO(PATH_NAME => '/usr/test'));

IFS_OBJECT_STATISTICS table function


The IFS_OBJECT_STATISTICS table function returns a table of objects contained in the starting path name
or accessible from the starting path name.
This information is similar to what is returned by the Retrieve Directory Information (RTVDIRINF)
command or the Qp0lGetAttr()--Get Attributes API.
No rows are returned for remote file system objects. This means that for the QNTC file system, only a
row for /QNTC is returned. For the Network File System (NFS) and QFileSvr.400 file systems, no rows are
returned.
Some file systems, including QDLS, are not threadsafe. Accessing information from these file systems
might not return some rows. If this happens, an error or warning is returned based on the
IGNORE_ERRORS parameter setting. See the Usage Notes® on this page for the list of threadsafe file
systems: access()--Determine File Accessibility.
Authorization: The caller must have:
For file systems other than QDLS and QSYS:

Database performance and query optimization 629


• For each directory included in the path name used to start the search, *X
• For each directory processed recursively, *RX and *OBJMGT
• For each object returned, *OBJMGT
For the QDLS file system:
• For each directory included in the path name, except for QDLS, used to start the search, *X
• For every object being returned or processed recursively, *RWX and *OBJEXIST *OBJMGT *OBJALTER
*OBJREF
For the QSYS file system:
• For the library or object included in the path name used to start the search, *USE
• For each library or object processed recursively by the service, *USE and *OBJMGT
• For each object returned, *OBJMGT
To return values for OBJECT_AUDIT and OBJECT_AUDIT_CREATE, the caller must have *ALLOBJ or
*AUDIT special authority.

IFS_OBJECT_STATISTICS ( start-path-name
START_PATH_NAME =>

, subtree-directories
SUBTREE_DIRECTORIES =>

, object-type-list
OBJECT_TYPE_LIST =>

, omit-list
OMIT_LIST =>

)
, ignore-errors
IGNORE_ERRORS =>

start-path- An expression that returns a path name for starting the search. A relative path name is
name relative to the current directory. If an absolute path name is not specified, the current
working directory is used in combination with the relative path name to resolve to the
object.
subtree- An expression that indicates whether all subdirectories should be recursively processed
directories or not.

NO Only objects in the directory identified by start-path-name are processed.


YES All subdirectories for the directory identified by start-path-name are processed.
This is the default.

object-type- A list of one or more object types that should be returned. One or more blanks separate
list multiple values. The default is the empty string, indicating all objects are returned.
Values include all the standard system object types, for example *PGM or *STMF, and
the following special values:

630 IBM i: Performance and Query Optimization


*ALLDIR Select all directory object types. This includes *LIB, *DIR, *FLR, *FILE, and
*DDIR object types.

*ALLSTMF Select all stream file object types. This includes *MBR, *DOC, *STMF,
*DSTMF, and *USRSPC object types.
*MBR Select all database file member types.

*NOQDLS Exclude all QDLS file system object types.


*NOQOPT Exclude all QOPT and QNTC file system object types.
*NOQSYS Exclude all QSYS.LIB object types. This includes all objects in the QSYS.LIB
file system and all independent ASP QSYS.LIB file systems which are
available when the function is invoked.

omit-list A character string containing one or more path names to exclude from processing. All
objects and sub directories accessed from this path are excluded as well. The default is
the empty string, indicating no path names are excluded from processing.
The root path ('/') must not be included in the list. If more than one path is provided, the
values are separated by one or more blanks. If a blank exists in a path name, the path
name must be enclosed in either apostrophes (') or quotes("). When delimiting a path
name and there is an apostrophe or quote (matching the enclosing character) in the path
name, the embedded character needs to be doubled. For example, the following are valid
path strings.
• One path name. No delimiter needed:
/dir1/dir2/content
• Two path names. No delimiter needed:
/dir1/content /dir1/dir3
• Blank in path name, path delimited with apostrophes:
'/dir1/content string'
• Two path names. Blank and apostrophe in first path. First path name is delimited with
apostrophes and the apostrophe in the name is doubled. Second path is does not need
to be delimited:
'/dir1/dir2/my file''s content' /dir4/test'123
• Two path names. Blank and apostrophe in first path. First path name is delimited with
quotes. Second path is delimited even though not required:
"/dir1/dir2/my file's content" "/dir4/test'123"

ignore-errors A character or graphic string expression that identifies what to do when an error is
encountered.

NO An error is returned.

YES A warning is returned.


No row is returned when an error is encountered. This is the default.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 143. IFS_OBJECT_STATISTICS table function

Column Name Data Type Description

PATH_NAME DBCLOB(16M) CCSID The path name of an integrated file system object.
1200

Database performance and query optimization 631


Table 143. IFS_OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

OBJECT_TYPE VARCHAR(10) The object type.

SYMBOLIC_LINK DBCLOB(16M) CCSID The symbolic link for this object.


1200
Contains the null value if OBJECT_TYPE is not *SYMLNK.

ASP_NUMBER INTEGER The auxiliary storage pool (ASP) in which the object is stored.
Contains the null value if the object does not reside on this IBM i.

TEXT_DESCRIPTION VARGRAPHIC(50) The text string associated with the object.


CCSID 1200
Contains the null value if there is no text string.

FILE_IDENTIFIER_NUMBER BIGINT The file identifier number of the object. This number uniquely identifies the
object with a file system.
The file identifier number, generation identifier, and file system identifier
used together uniquely identify the object on the system.

GENERATION_IDENTIFIER BIGINT The generation identifier associated with the object.


The file identifier number, generation identifier, and file system identifier
used together uniquely identify the object on the system.

FILE_SYSTEM_IDENTIFIER BIGINT The file system ID to which the object belongs. This number uniquely
identifies the file system to which the object belongs.
The file identifier number, generation identifier, and file system identifier
used together uniquely identify the object on the system.

FILE_IDENTIFIER BINARY(16) An identifier associated with the referred to object.

FILE_ACCESS BINARY(4) Bit string containing information including the file type and file mode

CREATE_TIMESTAMP TIMESTAMP(0) The time the object was created.

ACCESS_TIMESTAMP TIMESTAMP(0) The time that the object's data was last accessed.
Contains the null value if the object has never been accessed.

DATA_CHANGE_TIMESTAMP TIMESTAMP(0) The time that the object's data was last changed.
Contains the null value if the object's data has never been changed.

OBJECT_CHANGE_TIMESTAMP TIMESTAMP(0) The time that the object's data or attributes were last changed.
Contains the null value if the object's data or attributes have never been
changed.

LAST_USED_TIMESTAMP TIMESTAMP(0) The date the object was last used.


Contains the null value if the object has never been used or if usage data
is not maintained for the IBM i type or the file system to which an object
belongs.

DAYS_USED_COUNT INTEGER The number of days an object has been used. Usage has different meanings
according to the specific file system and according to the individual object
types supported within a file system. Usage can indicate the opening or
closing of a file or can refer to adding links, renaming, restoring, or checking
out an object. This count is incremented once each day that an object is
used and can be reset.

LAST_RESET_TIMESTAMP TIMESTAMP(0) The timestamp when the days used count was last reset to zero.
Contains the null value if the days used count has never been reset.

ALLOCATED_SIZE BIGINT The number of bytes that have been allocated for this object.

DATA_SIZE BIGINT The size, in bytes, of the data in this object. This size does not include object
headers or the size of extended attributes associated with the object.

CCSID INTEGER The CCSID of the data and extended attributes of the object.
Contains the null value if there is no CCSID.

CODE_PAGE INTEGER The code page derived from the coded character set identifier (CCSID) used
for the data in the file or the extended attributes of the directory.
Contains the null value if there is more than one code page or if the CCSID is
not a supported CCSID.

EXTENDED_ATTRIBUTE_COUNT BIGINT Number of extended attributes associated with this object.

CRITICAL_EXTENDED_ATTRIBUTE_COUNT BIGINT Number of critical extended attributes associated with this object.

632 IBM i: Performance and Query Optimization


Table 143. IFS_OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

EXTENDED_ATTRIBUTE_SIZE BIGINT The total number of extended attribute bytes.

HARD_LINK_COUNT INTEGER The number of hard links to the object.

OBJECT_READ_ONLY VARCHAR(3) Whether the object can be written to or deleted, have its extended
attributes changed or deleted, or have its size changed.

NO The object can be changed.

YES The object can only be read.

OBJECT_HIDDEN VARCHAR(3) Whether the object can be displayed using an ordinary directory listing.

NO The object is not hidden.

YES The object is hidden.

TEMPORARY_OBJECT VARCHAR(3) Whether the object is a temporary object.

NO The object is a permanent object.

YES The object is a temporary object.

SYSTEM_FILE VARCHAR(3) Whether the object is a system file and is excluded from normal directory
searches.

NO The object is not a system file.

YES The object is a system file.

SYSTEM_USAGE VARCHAR(6) Whether the file has a special use by the system.

NONE The file is a generic stream file.

NWSSTG The file is a network server storage space.

VRTVOL The file is a virtual volume. Examples include tape and optical
virtual volumes.

Contains the null value if OBJECT_TYPE is not *STMF.

DEVICE_SPECIAL_FILE BIGINT It the object is a device special file, the real device it represents.
Contains the null value if this is not a device special file.

OBJECT_OWNER VARCHAR(10) The name of the user profile that is the owner of the object. Can contain the
following special value:

*NOUSRPRF This special value is used by the Network File System to


indicate that there is no user profile on the local server on
the IBM i with a user ID (UID) matching the UID of the
remote object.

Contains the null value if there is no owner.

USER_ID_NUMBER BIGINT User ID (UID) number of the owner of the object.


Contains the null value if there is no owner.

PRIMARY_GROUP VARCHAR(10) The name of the user profile that is the primary group of the object. Can
contain the following special value:

*NOUSRPRF This special value is used by the Network File System to


indicate that there is no user profile on the local server on
the IBM i with a group ID (GID) matching the GID of the
remote object.

Contains the null value if the object has no primary group.

GROUP_ID_NUMBER BIGINT Group ID (GID) number of the user profile that is the primary group of the
object.
Contains the null value if the object has no primary group.

AUTHORIZATION_LIST VARCHAR(10) The name of the authorization list that is used to secure the named object.
Contains the null value if no authorization list is used in determining
authority to the object.

Database performance and query optimization 633


Table 143. IFS_OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

SET_EFFECTIVE_USER_ID VARCHAR(3) Set effective user ID (UID) at execution time.

NO The user ID (UID) is not set at execution time.

YES The object owner is the effective user ID (UID) at execution time.

Contains the null value if OBJECT_TYPE is *DIR.

SET_EFFECTIVE_GROUP_ID VARCHAR(3) Set effective group ID (GID) at execution time.

NO If the object is a file, the group ID (GID) is not set at execution


time. If the object is a directory in the "root" (/), QOpenSys, or
user-defined file systems, the group ID (GID) of objects created in
the directory is set to the effective GID of the thread creating the
object. This value cannot be set for other file systems.

YES If the object is a file, the group ID (GID) is set at execution time. If
the object is a directory, the group ID (GID) of objects created in the
directory is set to the GID of the parent directory.

AUTHORITY_COLLECTION_VALUE VARCHAR(10) Specifies the authority collection value used for the object when authority
collection for objects is active.

*NONE No authority information will be collected for this object when


authority collection for objects is active.
A value of *NONE will be returned if the object type is not
supported by authority collection.

*OBJINF Authority information will be collected for this object when


authority collection for objects is active. The authority
checking information is collected for each unique instance
of the object level information associated with the authority
check.

OBJECT_AUDIT VARCHAR(7) The auditing value associated with the object.

*ALL Audit all access to this object by all users on the system. All
access is defined as a read or change operation.

*CHANGE Audit all change access to this object by all users on the
system.

*NONE No auditing occurs for this object when it is read or changed


regardless of the user who is accessing the object.

*USRPRF Audit this object only if the current user is being audited. The
current user is tested to determine if auditing should be done
for this object. The user profile can specify if only change
access is audited or if both read and change accesses are
audited for this object.

Contains the null value if the user is not allowed to retrieve the current
auditing value.

OBJECT_AUDIT_CREATE VARCHAR(7) The create object auditing value associated with the directory. This is the
auditing value given to any objects created in the directory.

*ALL Audit all access to this object by all users on the system. All
access is defined as a read or change operation.

*CHANGE Audit all change access to this object by all users on the
system.

*NONE No auditing occurs for this object when it is read or changed


regardless of the user who is accessing the object.

*SYSVAL The object auditing value for the objects created in the
directory is determined by the system auditing value
(QCRTOBJAUD).

*USRPRF Audit this object only if the current user is being audited. The
current user is tested to determine if auditing should be done
for this object. The user profile can specify if only change
access is audited or if both read and change accesses are
audited for this object. The OBJAUD parameter of the Change
User Auditing (CHGUSRAUD) command is used to change the
auditing for a specific user.

Contains the null value if the user is not allowed to retrieve the current
create object auditing value.

634 IBM i: Performance and Query Optimization


Table 143. IFS_OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

JOURNALED VARCHAR(3) Current journaling status of the object.

NO The object is not currently being journaled.

YES The object is currently being journaled.

JOURNAL_LIBRARY VARCHAR(10) The name of the library containing the journal currently being used .
Contains the null value if the object is not journaled.

JOURNAL_NAME VARCHAR(10) The name of the journal currently being used.


Contains the null value if the object is not journaled.

JOURNAL_BEFORE_IMAGE VARCHAR(3) Indicates whether the image of the object before a change is journaled
when journaling is active.

NO The image of the object before a change is not journaled.

YES The image of the object before a change is journaled.

Contains the null value if the object has never been journaled.

JOURNAL_AFTER_IMAGE VARCHAR(3) Indicates whether the image of the object after a change is journaled when
journaling is active.

NO The image of the object after a change is not journaled.

YES The image of the object after a change is journaled.

Contains the null value if the object has never been journaled.

JOURNAL_IDENTIFIER VARCHAR(10) The journal identifier (JID) for this object.


Contains the null value if the object has never been journaled.

JOURNAL_START_TIMESTAMP TIMESTAMP(0) The timestamp when the object had most recently had journaling started for
it.
Contains the null value if the object has never been journaled.

JOURNAL_OPTIONAL_ENTRIES VARCHAR(3) When journaling is active, entries that are considered optional are journaled.
The list of optional journal entries varies for each object type. See
Integrated file system for information regarding these optional entries for
various objects.

NO Optional entries for this object are not journaled.

YES Optional entries for this object are journaled.

Contains the null value if the object has never been journaled.

JOURNAL_SUBTREE VARCHAR(3) Indicates whether this object is a directory or library with inherit journal
semantics.

NO This object does not use inherit journal semantics.

YES If this object is a directory, new objects created or linked within


this directory will inherit the journal options and state from this
directory.
If this object is a library, new objects created or linked within this
library will inherit the journal options and state from this library
according to the journal inherit rules for this library.

Contains the null value if the object has never been journaled.

Database performance and query optimization 635


Table 143. IFS_OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

PARTIAL_TRANSACTION CHAR(1) Indicates whether the object contains a partial transaction:

N The object does not contain a partial transaction.

R A rollback abnormally ended prior to completion.


It is recommended that the object be restored as it can not be used.
As a last resort, the Change Journaled Object (CHGJRNOBJ) command
can be used to allow the object to be used. Doing this, however, may
leave the object in an inconsistent state.

Y The object was saved while active with a partial transaction.


A subsequent restore of the object contains the partial transaction.
The user should apply changes from the journal to complete the
transaction.

Contains the null value if the object has never been journaled.

APPLY_STARTING_RECEIVER_LIBRARY VARCHAR(10) The name of the library that contains the journal receiver.
Contains the null value if the object has never been journaled.

APPLY_STARTING_RECEIVER VARCHAR(10) The oldest journal receiver needed to successfully Apply Journaled Changes
(APYJRNCHG). If PARTIAL_TRANSACTION has a value of Y, the journal
receiver contains the journal entries representing the start of the partial
transaction. Otherwise; the journal receiver contains the journal entries
representing the start-of-the-save operation.
Contains the null value if PARTIAL_TRANSACTION has a value of R. Also
contains the null value if the object has never been journaled.

APPLY_STARTING_RECEIVER_ASP VARCHAR(10) The name of the ASP for the library that contains the starting journal
receiver. Can contain the special value *SYSBAS.
Contains the null value if the object has never been journaled.

OBJECT_SIGNED VARCHAR(3) Whether an object has a digital signature.

NO The object does not have a digital signature.

YES The object does have a digital signature.

Contains the null value if OBJECT_TYPE is not *STMF.

SYSTEM_TRUSTED_SOURCE VARCHAR(3) Whether the object was signed by a source that is trusted by the system.

NO None of the signatures came from a source that is trusted by the


system.

YES The object was signed by a source that is trusted by the system.
If the object has multiple signatures, at least one of the signatures
came from a source that is trusted by the system.

Contains the null value if OBJECT_TYPE is not *STMF or if OBJECT_SIGNED


is NO.

MULTIPLE_SIGNATURES VARCHAR(3) Whether an object has more than one digital signature.

NO The object has only one digital signature.

YES The object has more than one digital signature. If


SYSTEM_TRUSTED_SOURCE is YES, at least one of the signatures
is from a source trusted by the system.

Contains the null value if OBJECT_TYPE is not *STMF or if OBJECT_SIGNED


is NO.

OBJECT_DOMAIN VARCHAR(7) The domain of the object.

*SYSTEM The object exists in system domain.

*USER The object exists in user domain.

BLOCK_SIZE INTEGER The block size of the object.

636 IBM i: Performance and Query Optimization


Table 143. IFS_OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

AUX_STORAGE_ALLOCATION VARCHAR(8) Determines how auxiliary storage is allocated by the system for the
specified object.

DYNAMIC The system will dynamically determine the optimal auxiliary


storage allocation for the object, balancing space used
versus disk I/O operations.

MINIMIZE The auxiliary storage will be allocated to minimize the space


used by the object. That is, as additional auxiliary storage
is required, it will be allocated in small sized extents to
accommodate the current space requirement. Accessing an
object composed of many small extents may increase the
number of disk I/O operations for that object.

NORMAL The auxiliary storage will be allocated normally. That is, as


additional auxiliary storage is required, it will be allocated
in logically sized extents to accommodate the current space
requirement, and anticipated future requirements, while
minimizing the number of disk I/O operations.

Contains the null value if OBJECT_TYPE is not *STMF.

AUX_STORAGE_OVERFLOW VARCHAR(3) Whether the object has overflowed the auxiliary storage pool it resides in.

NO The auxiliary storage pool is not overflowed.

YES The auxiliary storage pool is overflowed.

MAIN_STORAGE_ALLOCATION VARCHAR(8) Determines how main storage is allocated by the system for the specified
object.

DYNAMIC The system will dynamically determine the optimal main


storage allocation for the object depending on other system
activity and main storage contention. That is, when there is
little main storage contention, as much storage as possible
will be allocated and used to minimize the number of
disk I/O operations. When there is significant main storage
contention, less main storage will be allocated and used to
minimize the main storage contention.

MINIMIZE The main storage will be allocated to minimize the space


used by the object. That is, as little main storage as possible
will be allocated and used. This minimizes main storage
usage while increasing the number of disk I/O operations
since less information is cached in main storage.

NORMAL The main storage will be allocated normally. That is, as


much main storage as possible will be allocated and used.
This minimizes the number of disk I/O operations since the
information is cached in main storage.

Contains the null value if OBJECT_TYPE is not *STMF.

STORAGE_FREED VARCHAR(3) Whether the object's data has been moved offline, freeing its online storage.

NO The object's data is not offline.

YES The object's data is offline.

STORED_LOCAL VARCHAR(3) Indicates whether an object is stored locally or stored on a remote system.
The decision of whether a file is local or remote varies according to the
respective file system rules. Objects in file systems that do not carry either a
local or remote indicator are treated as remote.

NO The object's data is on a remote system.

YES The object's data is stored locally.

VIRTUAL_DISK_STORAGE VARCHAR(3) Whether the object is the storage which was allocated for Integrated
xSeries servers to use as virtual disk drives for the xSeries servers.

NO Object is not virtual disk storage.

YES Object is virtual disk storage.

Contains the null value if OBJECT_TYPE is not *STMF.

Database performance and query optimization 637


Table 143. IFS_OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

DIRECTORY_FORMAT CHAR(6) The format of the specified directory object.

*TYPE1 The directory has the original directory format. The Convert
Directory (CVTDIR) command may be used to convert from the
*TYPE1 format to the *TYPE2 format.

*TYPE2 The directory is optimized for performance, size, and reliability


compared to directories having the *TYPE1 format.

Contains the null value if OBJECT_TYPE is not *DIR.

STREAM_FILE_FORMAT CHAR(6) The format of the stream file.

*TYPE1 The object has the same format as *STMF objects created
on releases prior to V4R4. It has a minimum object size of
4096 bytes and a maximum object size of approximately 128
gigabytes.

*TYPE2 This format was introduced in V4R4. It has a minimum object


size of 4096 bytes and a maximum object size of approximately
one terabyte in the "root" (/), QOpenSys and user-defined
file systems. Otherwise, the maximum is approximately 256
gigabytes.

Contains the null value if OBJECT_TYPE is not *STMF.

UDFS_FILE_FORMAT CHAR(6) The default file format of stream files (*STMF) created in the user-defined
file system.

*TYPE1 The stream file (*STMF) has the same format as *STMFs created
on releases prior to V4R4. It has a minimum object size of
4096 bytes and a maximum object size of approximately 128
gigabytes.

*TYPE2 This format was introduced in V4R4. It has a minimum object


size of 4096 bytes and a maximum object size of approximately
one terabyte in the "root" (/), QOpenSys and user-defined
file systems. Otherwise, the maximum is approximately 256
gigabytes.

Contains the null value if OBJECT_TYPE is not *STMF.

UDFS_PREFERRED_STORAGE CHAR(3) The preferred storage media for the objects in the UDFS.

ANY No storage media is preferred. Storage will be allocated from any


available storage media.

SSD Solid state drive storage media is preferred. Storage should be


allocated from solid state drive storage media, if available.

Contains the null value if the preferred storage media is not known.

UDFS_TEMPORARY_OBJECT VARCHAR(3) Whether the objects in the UDFS are temporary objects.

NO The objects in the UDFS are permanent objects.

YES The objects in the UDFS are temporary objects.

CASE_SENSITIVE_FILE_SYSTEM VARCHAR(3) The case sensitivity of the file system that contains this object.

NO The file system is not case sensitive.

YES The file system is case sensitive.

RESTRICT_RENAME_AND_UNLINK VARCHAR(3) Restricted renames and unlinks for objects within a directory. Objects can
be linked into a directory that has this attribute set on, but cannot be
renamed or unlinked from it unless one or more of the following are true for
the user performing the operation:
• The user is the owner of the object.
• The user is the owner of the directory.
• The user has *ALLOBJ special authority.

NO No additional restrictions for rename and unlink operations.

YES Additional restrictions for rename and unlink operations.

638 IBM i: Performance and Query Optimization


Table 143. IFS_OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

PC_ARCHIVE VARCHAR(3) Whether the object has changed since the last time it was saved on the PC.

NO The object has not changed.

YES The object has changed.

SYSTEM_ARCHIVE VARCHAR(3) Whether the object has changed and needs to be saved on the IBM i. The
value will be YES when an object's change time is updated, and set to NO
when the object has been saved.

NO The object has not changed and does not need to be saved.

YES The object has changed and needs to be saved.

ALLOW_SAVE VARCHAR(3) Whether the object can be saved or not.

NO This object will not be saved when using the Save Object (SAV)
command or the QsrSave() API.
Additionally, if this object is a directory, none of the objects in
the directory's subtree will be saved unless they were explicitly
specified as an object to be saved.

YES This object will be saved when using the Save Object (SAV)
command or the QsrSave() API.

SYSTEM_RESTRICT_SAVE VARCHAR(3) Whether the system prevents the object from being saved.

NO The system does not prevent the object from being saved.

YES The system has determined that the object cannot be saved
because of system restrictions.

INHERIT_ALLOW_CHECKPOINT_WRITER VARCHAR(3) Whether new objects created within a directory should inherit the save-
while-active checkpoint processing options of its parent.

NO New directory objects created within this directory will have the
QP0L_ATTR_INHERIT_ALWCKPWRT attribute set to NO.
New objects created within this directory will
have the QP0L_ATTR_ALWCKPWRT attribute set to
QP0L_NOT_ALWCKPWRT.

YES New directory objects created within this directory will have the
QP0L_ATTR_INHERIT_ALWCKPWRT attribute set to YES.
New objects created within this directory will have the
QP0L_ATTR_ALWCKPWRT attribute set to QP0L_ALWCKPWRT.

ALLOW_WRITE_DURING_SAVE VARCHAR(3) If the object is a stream file, indicates whether the stream file can be shared
with readers and writers during save-while-active checkpoint processing. If
the object is a directory, indicates whether links can be added, removed, or
renamed in the directory during a save-while-active operation.

NO If the object is a stream file, it can be shared with readers only


during save-while-active checkpoint processing. If the object is
a directory, links can not be added, removed, or renamed in the
directory during a save-while-active operation.

YES If the object is a stream file, it can be shared with readers


and writers during save-while-active checkpoint processing. If the
object is a directory, links can be added, removed, or renamed in the
directory during a save-while-active operation.

Contains the null value if OBJECT_TYPE is not *STMF or *DIR.

Database performance and query optimization 639


Table 143. IFS_OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

EXIT_PROGRAM_SCAN VARCHAR(11) Whether the object will be scanned when exit programs are registered with
any of the integrated file system scan-related exit points.

CHANGE The object will be scanned according to the rules described


ONLY in the scan-related exit programs only if the object has been
modified since the last time the object was scanned. It will
not be scanned if the scanning software has been updated.
This attribute only takes effect if the Scan file systems
control (QSCANFSCTL) system value has *USEOCOATR
specified. Otherwise, it will be treated the same as YES.

NO The object will not be scanned according to the rules


described in the scan-related exit programs.

YES The object will be scanned according to the rules described


in the scan-related exit programs if the object has been
modified or if the scanning software has been updated since
the last time the object was scanned.

Contains the null value if OBJECT_TYPE is not *STMF.

EXIT_PROGRAM_SCAN_DIRECTORY VARCHAR(11) Whether the objects created in a directory will be scanned when exit
programs are registered with any of the integrated file system scan-related
exit points.

CHANGE After an object is created in the directory, the object will be


ONLY scanned according to the rules described in the scan-related
exit programs only if the object has been modified since the
last time the object was scanned. It will not be scanned if
the scanning software has been updated. This attribute only
takes effect if the Scan file systems control (QSCANFSCTL)
system value has *USEOCOATR specified. Otherwise, it will
be treated the same as YES.

NO After an object is created in the directory, the object will


not be scanned according to the rules described in the scan-
related exit programs.

YES After an object is created in the directory, the object will


be scanned according to the rules described in the scan-
related exit programs if the object has been modified or if the
scanning software has been updated since the last time the
object was scanned.

Contains the null value if OBJECT_TYPE is not *DIR.

SCAN_STATUS VARCHAR(12) The scan status associated with this object.

FAILURE The object has been scanned by a scan-related exit


program, and at the time of that last scan request,
the object failed the scan and the operation did not
complete. Once an object has been marked as a failure,
it will not be scanned again until the object's scan
signature is different than the global scan key signature or
independent ASP group scan key signature as appropriate.
Therefore, subsequent requests to work with the object
will fail with a scan failure indication if that access meets
the criteria for when an object is to be scanned.

NOT The object does not require any scanning because the
REQUIRED object is marked to not be scanned.

PENDING The object is in a file system that has not completely


converted to the *TYPE2 directory format, and therefore
will not be scanned until the file system is completely
converted.

REQUIRED A scan is required for the object either because it has not
yet been scanned by the scan-related exit programs, or
because the object data or CCSID has been modified since
it was last scanned.

SUCCESS The object has been scanned by a scan-related exit


program, and at the time of that last scan request, the
object did not fail the scan.

640 IBM i: Performance and Query Optimization


Table 143. IFS_OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

CCSID_SCAN INTEGER A CCSID value that the object has been scanned in if it was previously
scanned in a CCSID. If SCAN_STATUS is SUCCESS, the object was
successfully scanned in this CCSID. If SCAN_STATUS is FAILURE, the object
failed the scan in this CCSID.
Contains the null value if no CCSID applies.

CCSID_SCAN_SUCCESS INTEGER If SCAN_STATUS is SUCCESS, the object was successfully scanned in this
CCSID.
Contains the null value if the SCAN_STATUS is FAILURE or if CCSID_SCAN is
the null value.

SCAN_SIGNATURES_DIFFERENT VARCHAR(3) When an object is in an independent ASP group, the object scan signature
is compared to the associated independent ASP group scan signature. When
an object is not in an independent ASP group, the object scan signature is
compared to the global scan signature value.

NO The compared signatures are not different.

YES The compared signatures are different.

BINARY_SCAN VARCHAR(3) The object was scanned in binary mode when it was previously scanned.

NO The object was not scanned in binary mode.

YES The object was scanned in binary mode.

CHECKED_OUT VARCHAR(3) Whether the object is checked out.

NO The object is not checked out.

YES The object is checked out.

CHECKED_OUT_TIMESTAMP TIMESTAMP(0) The time the object was checked out.


Contains the null value if the object is not checked out.

CHECKED_OUT_USER VARCHAR(10) The user who has the object checked out.
Contains the null value if the object is not checked out.

Example
• List basic information for all the objects in directory /usr.

SELECT PATH_NAME, OBJECT_TYPE, DATA_SIZE, OBJECT_OWNER


FROM TABLE (QSYS2.IFS_OBJECT_STATISTICS(START_PATH_NAME => '/usr',
SUBTREE_DIRECTORIES => 'NO'));

• List basic information for all the objects in /usr, processing all subdirectories as well.

SELECT PATH_NAME, OBJECT_TYPE, DATA_SIZE, OBJECT_OWNER


FROM TABLE (QSYS2.IFS_OBJECT_STATISTICS(START_PATH_NAME => '/usr',
SUBTREE_DIRECTORIES => 'YES'));

IFS_READ, IFS_READ_BINARY, and IFS_READ_UTF8 table functions


The IFS_READ, IFS_READ_BINARY, and IFS_READ_UTF8 table functions read an integrated file system
stream file identified by path-name. The file's data is returned as character, binary, or UTF-8 data. It can
be returned as one string of data, or it can be broken into multiple lines using a specified length or end of
line characters.
Authorization: The caller must have:
• For objects not in the QSYS.LIB file system:
– Execute (*X) data authority to each directory preceding the stream file being read and
– Read (*R) data authority to the stream file
• For objects in the QSYS.LIB file system:

Database performance and query optimization 641


– Execute (*X) data authority to each directory preceding the object being read and
- For a *SAVF object, Read, Write, and Execute (*RWX) data authority to the object
- For all other object types, Read (*R) data authority to the object

IFS_READ ( path-name

IFS_READ_BINARY PATH_NAME =>

IFS_READ_UTF8

, maximum-line-length
MAXIMUM_LINE_LENGTH =>

, end-of -line
END_OF_LINE =>

)
, ignore-errors
IGNORE_ERRORS =>

The schema is QSYS2.

path-name An expression that returns the path name identifying the stream file to read. A relative
path name is relative to the current directory. If an absolute path name is not specified,
the current working directory is used in combination with the relative path name to
resolve to the object. If the object is not a stream file, an error is issued.
maximum- An integer value that specifies the maximum number of characters returned for each line.
line-length It must be greater than 0. The default is 2 gigabytes.
If end-of-line is NONE or if no end of line sequence is found in the stream file, the number
of characters returned for each line will be limited to this value.
If an end of line sequence is encountered before this length is reached, the line will end
at that point. The next line returned will start with the character directly after the end of
line sequence.
end-of-line A character or graphic string that specifies the end of line characters to be recognized in
the stream file. Each occurrence of an end of line sequence determines a line which is
returned. The end of line character sequence is not returned with the line. When using
IFS_READ_BINARY, end of line characters are never processed, so this parameter must
have a value of NONE.
The carriage-return character is always X'0D'. Based on the CCSID of the stream file being
read, the line feed character is X'25' for an EBCDIC CCSID and X'0A' for ASCII and UTF-8
CCSIDs.

ANY Any of the four end of line sequences indicate the end of a line. This is the
default for IFS_READ and IFS_READ_UTF8.
CR A carriage return indicates the end of a line.
CRLF A carriage return and line feed indicate the end of a line.
LF A line feed indicates the end of a line.
LFCR A line feed and carriage return indicate the end of a line.
NONE No end of line characters are recognized. maximum-line-length determines the
number of characters to be returned. This is the default for IFS_READ_BINARY.

642 IBM i: Performance and Query Optimization


ignore-errors A character or graphic string expression that identifies what to do when an error is
encountered.

NO An error is returned.

YES A warning is returned.


No row is returned when an error is encountered. This is the default.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 144. IFS_READ table function

Column Name Data Type Description

LINE_NUMBER INTEGER Relative position of this line in the stream file.

LINE For IFS_READ: The data for this line.


CLOB(2G) • For IFS_READ, the data from the stream file will be returned in the job CCSID.

For IFS_READ_BINARY: • For IFS_READ_BINARY, the data from the stream file will be returned exactly
BLOB(2G) as it is stored without conversion.
• For IFS_READ_UTF8, the data from the stream file will be returned in CCSID
For IFS_READ_UTF8: 1208.
CLOB(2G) CCSID 1208

Example
• Read the data from stream file /usr/file1. Break lines when a carriage return/line feed sequence is
encountered. The result will be in the job's CCSID.

SELECT * FROM TABLE(QSYS2.IFS_READ(PATH_NAME => '/usr/file1',


END_OF_LINE => 'CRLF'));

• Read the data from stream file /usr/file2. If the file size is less than 2 gigabytes, the result will be a
single row containing the entire file. If the file size is greater than 2 gigabytes, multiple rows will be
returned.

SELECT * FROM TABLE(QSYS2.IFS_READ_BINARY(PATH_NAME => '/usr/file2'));

IFS_RENAME scalar function


The IFS_RENAME scalar function renames either a file or a directory in the Integrated File System.
The function requires that Option 13 (System Openness Includes) of the IBM i operating system is
installed.
This function uses the Qp0lRenameUnlink()--Rename File or Directory, Unlink "new" If It Exists and
Qp0lRenameKeep()--Rename File or Directory, Keep "new" If It Exists APIs to rename the object. Refer to
the APIs for more detailed information.
Authorization: See Note below.

IFS_RENAME ( from-object
FROM_OBJECT =>

, to-object
TO_OBJECT =>

)
, replace
REPLACE =>

Database performance and query optimization 643


The schema is SYSTOOLS.

from-object A character string containing the path of the file or directory to be renamed.
to-object A character string containing the new path name for the file or directory. If to-object exists,
from-object and to-object must both be files or must both be directories.
replace A character string that indicates whether an existing file or directory is replaced.

NO An existing file or directory will not be replaced. If it already exists, the rename
request will fail. This is the default.
YES An existing file or directory will be replaced.

When replacing a directory, the replaced directory must be empty.

The result of the function is an integer. If the replace is successful, the function returns a value of 0. If the
replace returns an error, the function returns the errno value from the API.

Note
This function is provided in the SYSTOOLS schema as an example of how to embed a C language interface
in an SQL scalar function. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can
be extracted and used as a model for building similar helper functions, or to create a customized version
within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Rename /usr/resultfile.txt to /usr/resultfileyymmdd.txt, where yymmdd is today's date.

VALUES SYSTOOLS.IFS_RENAME(
FROM_OBJECT => '/usr/resultfile.txt',
TO_OBJECT => '/usr/resultfile' concat
varchar_format(current date, 'YYMMDD') concat
'.txt',
REPLACE => 'NO'
);

IFS_UNLINK scalar function


The IFS_UNLINK scalar function deletes an Integrated File System (IFS) stream file.
The function requires that Option 13 (System Openness Includes) of the IBM i operating system is
installed.
This function uses the unlink()--Remove Link to File API to delete or unlink the object.
Authorization: See Note below.

IFS_UNLINK ( path-name )
PATH_NAME =>

The schema is SYSTOOLS.

path-name A character string containing the path of the file to be unlinked.


The result of the function is an integer. If the unlink is successful, the function returns a value of 0. If the
unlink returns an error, the function returns the errno value from the API.

644 IBM i: Performance and Query Optimization


Note
This function is provided in the SYSTOOLS schema as an example of how to embed a C language interface
in an SQL scalar function. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can
be extracted and used as a model for building similar helper functions, or to create a customized version
within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Unlink file /usr/reportdata.txt.

VALUES SYSTOOLS.IFS_UNLINK(PATH_NAME => '/usr/reportdata.txt');

IFS_WRITE, IFS_WRITE_BINARY, and IFS_WRITE_UTF8 procedures


The IFS_WRITE, IFS_WRITE_BINARY, and IFS_WRITE_UTF8 procedures write data to an integrated file
system stream file. The data can be written as character, binary, or UTF-8 data. Data can be either
replaced or appended for an existing file, or a new file can be created.
Up to 2 gigabytes of data can be written by one call to this procedure. It can contain embedded end of line
characters, or the procedure can append end of line characters to the input data.
Authorization: The caller must have:
• For objects not in the QSYS.LIB file system when the stream file exists and is not being replaced:
– Execute (*X) data authority to each directory preceding the stream file being written and
– Write (*W) data authority to the stream file
• For objects not in the QSYS.LIB file system when the stream file does not exist or is being replaced:
– Execute (*X) data authority to each directory preceding the stream file being written and
– Write and Execute (*WX) authority to the parent directory of the stream file
• For objects in the QSYS.LIB file system when the object exists and is not being replaced:
– Execute (*X) data authority to each directory preceding the object being written and
- For a *SAVF object, Read, Write, and Execute (*RWX) data authority to the object
- For all other object types, Write (*W) data authority to the object
• For objects in the QSYS.LIB file system when the object does not exist or is being replaced:
– Execute (*X) data authority to each directory preceding the object being written and
- For a *SAVF object, Read and Execute and Add (*RX and *ADD) data authority to the parent
directory of the object
- For a physical file member, Add (*ADD) data authority to the parent directory of the object
- For all other object types, *OBJMGT or *OBJALTER authority to the parent directory of the object

Database performance and query optimization 645


IFS_WRITE ( path-name

IFS_WRITE_BINARY PATH_NAME =>

IFS_WRITE_UTF8

, line
LINE => , file-ccsid
FILE_CCSID =>

, overwrite
OVERWRITE =>

)
, end-of-line
END_OF_LINE =>

The schema is QSYS2.

path- A character or graphic string that defines the path name for the file to be written. If an
name absolute path name is not specified, the current working directory is used in combination
with the relative path name to resolve to the object.
If path-name identifies an existing object, the object must be a stream file. Otherwise, a
stream file will be created.
When a stream file is created, the default authority for the parent directory is used.
line A character or graphic string containing the data to be written to the stream file at path-
name. It can be up to 2 gigabytes long.
• For IFS_WRITE, line is a character string in the job CCSID. If the stream file is not in the
job CCSID, line will be converted to the stream file's CCSID as it is written.
• For IFS_WRITE_BINARY, line is a binary string. The data will not be converted when
writing to the stream file.
• For IFS_WRITE_UTF8, line is a UTF-8 string. If the stream file is not UTF-8, line will be
converted to the stream file's CCSID as it is written.

file-ccsid An integer value that specifies the CCSID to be used when creating a new stream file. This
parameter is ignored when appending to an existing file.
If this parameter is not specified, the default is 1208 for IFS_WRITE_UTF8 and 0 for
IFS_WRITE and IFS_WRITE_BINARY.
When file-ccsid is 0, the job CCSID is used when creating a new stream file.
overwrite A character or graphic string that specifies whether the write operation appends to the
stream file, replaces the stream file, or fails when a stream file with the specified name
already exists.

APPEND The data in line is added to the end of the existing stream file. If the stream file
does not exist, it is created. This is the default.
NONE The write operation fails if the stream file exists.
REPLACE The data in line replaces the existing stream file if it exists. An existing stream
file is deleted and a new stream file is created. The CCSID of the stream file
might change. If the stream file does not exist, it is created.

646 IBM i: Performance and Query Optimization


end-of- A character or graphic string that specifies the end of line characters to write to the stream
line file after line is written. When using IFS_WRITE_BINARY, end of line characters are never
appended, so this parameter must have a value of NONE.
The carriage-return character is always X'0D'. Based on the CCSID of the stream file being
written, the line feed character is X'25' for an EBCDIC CCSID and X'0A' for ASCII and UTF-8
CCSIDs.

CR A carriage return is appended.


CRLF A carriage return and line feed are appended. This is the default for IFS_WRITE and
IFS_WRITE_UTF8.
LF A line feed is appended.
LFCR A line feed and carriage return are appended.
NONE No end of line characters are appended. This is the default for
IFS_WRITE_BINARY.

Examples
• Create a stream file which contains a list of all of the libraries on the system, one per line. The file is
created in job CCSID.

BEGIN
-- Make sure output file is empty to start
CALL QSYS2.IFS_WRITE(PATH_NAME =>'/tmp/library_names',
LINE => '',
OVERWRITE => 'REPLACE',
END_OF_LINE => 'NONE');

-- Add lines to the output file


FOR SELECT OBJNAME AS LIBNAME FROM TABLE(QSYS2.OBJECT_STATISTICS('*ALLSIMPLE', 'LIB')) DO
CALL QSYS2.IFS_WRITE(PATH_NAME => '/tmp/library_names',
LINE => LIBNAME);
END FOR;
END;

The QSYS2.IFS_READ table function can be used to read the contents of the generated stream file.

SELECT * FROM TABLE(QSYS2.IFS_READ('/tmp/library_names'));

• Create a UTF-8 (CCSID 1208) stream file which contains a UTF-8 Byte Order Mark (BOM) and the string
'Hello'.

CALL QSYS2.IFS_WRITE_BINARY(PATH_NAME => '/usr/utf8file',


LINE => BLOB(X'EFBBBF48656C6C6F'),
FILE_CCSID => 1208,
OVERWRITE => 'REPLACE'
);

SERVER_SHARE_INFO view
The SERVER_SHARE_INFO view returns information about IBM i NetServer shares.
This information is similar to what is returned by the List Server Information (QZLSLSTI) and Open List of
Server Information (QZLSOLST) APIs.
Authorization: None required.

The following table describes the columns in the view. The system name is SHARE_INFO. The schema is
QSYS2.

Database performance and query optimization 647


Table 145. SERVER_SHARE_INFO view

Column Name System Column Name Data Type Description

SERVER_SHARE_NAME SHARE VARCHAR(12) The network name of the resource.

SHARE_TYPE SHARE_TYPE VARCHAR(5) The type of share.

FILE This is a file share

PRINT This is a print share

TEXT_DESCRIPTION TEXT VARCHAR(50) An optional comment about the shared resource


or computer.
Nullable
Contains the null value if there is no text
description.

ENCRYPTION_REQUIRED ENCRYPTION VARCHAR(3) Whether the server requires access to the share
to use encryption.

NO Access to the share does not require


encryption

YES Access to the share can only be made


from an SMB 3 or newer client with
encryption enabled. Unencrypted access
to this share is denied.

The following columns can contain values when SHARE_TYPE is FILE. They will contain the null value when SHARE_TYPE is PRINT.

PATH_NAME PATH_NAME DBCLOB(16M) CCSID The file share path in the integrated file system.
1200
Contains the null value when SHARE_TYPE is
Nullable PRINT.

PERMISSIONS PERMISSION VARCHAR(3) Permissions to be applied against the file for


sharing.
Nullable
*R Read only

*RW Read/write

Contains the null value when SHARE_TYPE is


PRINT.

MAXIMUM_CONNECTIONS MAX_CONN INTEGER The maximum number of concurrent connections


that the shared file resource can accommodate.
Nullable
Contains the null value if the number is unlimited
or SHARE_TYPE is PRINT.

CURRENT_CONNECTIONS CUR_CONN INTEGER The number of connections that are currently


made to the resource.
Nullable
Contains the null value if the value could not be
returned or SHARE_TYPE is PRINT.

TEXT_CONVERSION_ENABLED TEXT_CONV VARCHAR(5) Whether the server enables text file data
conversion for this file share.
Nullable
MIXED Text conversion enabled and mixed
data is allowed

NO Text conversion not enabled

YES Text conversion enabled

Contains the null value when SHARE_TYPE is


PRINT.

TEXT_CONVERSION_CCSID TEXT_CCSID INTEGER The CCSID that is used for text file data
conversion. If the value is 0, no CCSID was
Nullable specified so the IBM i NetServer's default CCSID
will be used.
Contains the null value if
TEXT_CONVERSION_ENABLED is NO or when
SHARE_TYPE is PRINT.

648 IBM i: Performance and Query Optimization


Table 145. SERVER_SHARE_INFO view (continued)

Column Name System Column Name Data Type Description

FILE_EXTENSION_COUNT EXT_COUNT INTEGER The number of file extension entries returned in


FILE_EXTENSIONS.
Nullable
Contains the null value when SHARE_TYPE is
PRINT.

FILE_EXTENSIONS EXTENSIONS VARBINARY(5000) A string containing a list of file extensions. The


format of each entry is a 2 byte integer length
Nullable followed by that number of characters followed
by a single blank. If there are more file extensions
than what fit in this column, the last file extension
in the list will have a length of 3 with a value of
+++ to indicate the list was truncated.
Examples of extensions are:

* The server will convert


all files.

. The server will convert


all files without an
extension.

TXT, .TXT The server will


convert all files ending
with .TXT (that is, a.TXT,
a.b.c.TXT).

..TXT, ...TXT, ......TXT Extensions with more


than one leading period
will have no effect
on the server. No
translation will be done.

T*T The server will convert


all files ending with
an extension that
substitutes any number
of characters for the
* wild card (that is,
a.T123T, b.TXT, c.TEST).

T?T The server will convert


all files ending with
an extension that
substitutes any one
character for the ? wild
card (that is, a.T1T,
b.TXT).

Contains the null value when SHARE_TYPE is


PRINT.

The following columns can contain values when SHARE_TYPE is PRINT. They will contain the null value when SHARE_TYPE is FILE.

SPOOLED_FILE_TYPE SPOOL_TYPE VARCHAR(9) The type of spooled files that will be created using
this print share.
Nullable
AFP Advanced Function Presentation

AUTOSENSE Automatic type sensing

SCS Simplified Character Set

USERASCII User ASCII

Contains the null value when SHARE_TYPE is


FILE.

OUTPUT_QUEUE_LIBRARY OUTQLIB VARCHAR(10) The library containing the output queue.

Nullable Contains the null value when SHARE_TYPE is


FILE.

OUTPUT_QUEUE OUTQ VARCHAR(10) The name of the output queue.

Nullable Contains the null value when SHARE_TYPE is


FILE.

Database performance and query optimization 649


Table 145. SERVER_SHARE_INFO view (continued)

Column Name System Column Name Data Type Description

PRINT_DRIVER PRT_DRIVER VARCHAR(50) The text string that identifies the print driver
appropriate for this print share. When personal
Nullable computers connect to this shared printer, this
identifies the print driver they should use.
This text should match the name of a print
driver known to the personal computer operating
system.
Contains the null value when there is no print
driver or when SHARE_TYPE is FILE.

PRINTER_FILE_LIBRARY PRTF_LIB VARCHAR(10) The library containing the printer file.

Nullable Contains the null value when there is no printer


file or when SHARE_TYPE is FILE.

PRINTER_FILE PRTF VARCHAR(10) The name of the printer file.

Nullable Contains the null value when there is no printer


file or when SHARE_TYPE is FILE.

PUBLISH_PRINT_SHARE PUBLISH VARCHAR(3) Whether the print share is to be published

Nullable NO Print share is not published

YES Print share is published

Contains the null value when SHARE_TYPE is


FILE.

Example
• List all the file shares.

SELECT * FROM QSYS2.SERVER_SHARE_INFO


WHERE SHARE_TYPE = 'FILE';

Java Services
This view and procedure provide Java information and JVM management options.

JVM_INFO table function


The JVM_INFO table function returns information about active Java Virtual Machine (JVM) jobs. A default
wait time can be set for a JVM response.
The information returned is similar to the detail available through the Work with JVM Jobs (WRKJVMJOB)
CL command.
Authorization: The caller must have *JOBCTL special authority to see values for columns other than the
job name columns and PROCESS_ID.

JVM_INFO ( )
wait-time
WAIT_TIME =>

The schema is QSYS2.

wait- An integer value that provides the amount of time to wait, in seconds, for a JVM to return
time information. Valid values are 1 to 120.
Values other than 1, 2, 3, 4, 5, 10, 30, 60, and 120 will be rounded up to the next higher value.
The default is 3 seconds.
When a timeout occurs, values are returned for the job name columns and the PROCESS_ID
column.

650 IBM i: Performance and Query Optimization


The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 146. JVM_INFO table function

Column Name Data Type Description

JOB_NAME VARCHAR(28) The qualified job name for the active JVM.

JOB_NAME_SHORT VARCHAR(10) The name of the job for the active JVM.

JOB_USER VARCHAR(10) The user profile that started the job for the active JVM.

JOB_NUMBER VARCHAR(6) The job number of the job for the active JVM.

PROCESS_ID INTEGER The process identifier used by the kernel to uniquely identify the process.

START_TIME TIMESTAMP The current time when the JVM was started.

INITIAL_THREAD_TASKCOUNT BIGINT The taskcount or TDE number of the JVM's initial thread. The taskcount or
TDE number is a unique identifier assigned to each job, thread, and task
running in the system.

JAVA_THREAD_COUNT BIGINT The current number of java threads within the JVM job.

TOTAL_GC_TIME BIGINT Total time spent performing garbage collection tasks in milliseconds.

GC_CYCLE_NUMBER INTEGER The current or last garbage collection cycle performed.

GC_POLICY_NAME VARGRAPHIC(16) The name of the garbage collection policy in use.

CCSID 1200

JAVA_HOME VARGRAPHIC(1024) The java.home environment variable value in effect for this JVM.

CCSID 1200 This value indicates the JDK that is used when running a Java application.
The location of the Java tools and utilities is in one of two directories, either
<JAVA_HOME>/jre/bin or <JAVA_HOME>/bin, where <JAVA_HOME> is the
value of the JAVA_HOME environment variable. For example, if JAVA_HOME
is set to /QOpenSys/QIBM/ProdData/JavaVM/jdk60/32bit, indicating that IBM
Technology for Java 6 32-bit is to be used, then the Java tools and utilities
directories would be:
/QOpenSys/QIBM/ProdData/JavaVM/jdk60/32bit/bin
/QOpenSys/QIBM/ProdData/JavaVM/jdk60/32bit/jre/bin

USER_DIRECTORY VARGRAPHIC(1024) The user working directory for the JVM.

CCSID 1200 This also indicates the location where diagnostic detail will be dumped for the
JVM.

NUM_CURRENT_PROPERTIES INTEGER Total number of Java system properties currently present.

INITIAL_HEAP_SIZE BIGINT The initial heap size available to the JVM code, in kilobytes.

CURRENT_HEAP_SIZE BIGINT The amount of memory, in kilobytes, currently allocated for heap space.

IN_USE_HEAP_SIZE BIGINT The amount of memory, in kilobytes, currently in use by the heap.

MAX_HEAP_SIZE BIGINT The maximum heap size available to the JVM code, in kilobytes.

MALLOC_MEMORY_SIZE BIGINT The amount of memory, in kilobytes, that has been allocated with malloc().

INTERNAL_MEMORY_SIZE BIGINT The amount of memory, in kilobytes, that the JVM is using for internal
operations.

JIT_MEMORY_SIZE BIGINT The size of the memory space, in kilobytes, that is used by the JIT (Just in
Time) compiler.

SHARED_CLASS_SIZE BIGINT The amount of memory, in kilobytes, that the JVM is using for shared classes.

BIT_MODE INTEGER The Java version of this job.

32 32 bit Java job

64 64 bit Java job

Example
• Show information for all JVMs on the system. Do not wait longer than 10 seconds for the results of any
individual JVM to be returned.

SELECT * FROM TABLE(QSYS2.JVM_INFO(WAIT_TIME => 10));

Database performance and query optimization 651


JVM_INFO view
The JVM_INFO view returns information about active Java Virtual Machine (JVM) jobs.
The information returned is similar to the detail available through the Work with JVM Jobs (WRKJVMJOB)
CL command.
Authorization: The caller must have *JOBCTL special authority to see values for columns other than the
job name columns and PROCESS_ID.
The following table describes the columns in the view. The schema is QSYS2.
Table 147. JVM_INFO view

System Column
Column Name Name Data Type Description

JOB_NAME JOB_NAME VARCHAR(28) The qualified job name for the active JVM.

JOB_NAME_SHORT JOB_NAME_S VARCHAR(10) The name of the job for the active JVM.

JOB_USER JOB_USER VARCHAR(10) The user profile that started the job for the active JVM.

JOB_NUMBER JOB_NUMBER VARCHAR(6) The job number of the job for the active JVM.

PROCESS_ID PROCESS_ID INTEGER The process identifier used by the kernel to uniquely identify the
process.

START_TIME START_TIME TIMESTAMP The current time when the JVM was started.

INITIAL_THREAD_TASKCOUNT INITTHDNUM BIGINT The taskcount or TDE number of the JVM's initial thread. The
taskcount or TDE number is a unique identifier assigned to each
job, thread, and task running in the system.

JAVA_THREAD_COUNT JAVATHDNUM BIGINT The current number of java threads within the JVM job.

TOTAL_GC_TIME ACCUMTIME BIGINT Total time spent performing garbage collection tasks in
milliseconds.

GC_CYCLE_NUMBER GCCYCLE INTEGER The current or last garbage collection cycle performed.

GC_POLICY_NAME GCPOLICY VARGRAPHIC(16) The name of the garbage collection policy in use.

CCSID 1200

JAVA_HOME JAVA_HOME VARGRAPHIC(102 The java.home environment variable value in effect for this JVM.
4)
This value indicates the JDK that is used when running a
CCSID 1200 Java application. The location of the Java tools and utilities
is in one of two directories, either <JAVA_HOME>/jre/bin or
<JAVA_HOME>/bin, where <JAVA_HOME> is the value of the
JAVA_HOME environment variable. For example, if JAVA_HOME is
set to /QOpenSys/QIBM/ProdData/JavaVM/jdk60/32bit, indicating
that IBM Technology for Java 6 32-bit is to be used, then the Java
tools and utilities directories would be:
/QOpenSys/QIBM/ProdData/JavaVM/jdk60/32bit/bin
/QOpenSys/QIBM/ProdData/JavaVM/jdk60/32bit/jre/bin

USER_DIRECTORY USER_DIR VARGRAPHIC(102 The user working directory for the JVM.
4)
This also indicates the location where diagnostic detail will be
CCSID 1200 dumped for the JVM.

NUM_CURRENT_PROPERTIES NUMPROP INTEGER Total number of Java system properties currently present.

INITIAL_HEAP_SIZE INITHEAP BIGINT The initial heap size available to the JVM code, in kilobytes.

CURRENT_HEAP_SIZE CURHEAP BIGINT The amount of memory, in kilobytes, currently allocated for heap
space.

IN_USE_HEAP_SIZE INUSEHEAP BIGINT The amount of memory, in kilobytes, currently in use by the heap.

MAX_HEAP_SIZE MAXHEAP BIGINT The maximum heap size available to the JVM code, in kilobytes.

MALLOC_MEMORY_SIZE MALLOCSIZE BIGINT The amount of memory, in kilobytes, that has been allocated with
malloc().

INTERNAL_MEMORY_SIZE INTMEM BIGINT The amount of memory, in kilobytes, that the JVM is using for
internal operations.

JIT_MEMORY_SIZE JITSIZE BIGINT The size of the memory space, in kilobytes, that is used by the JIT
(Just in Time) compiler.

652 IBM i: Performance and Query Optimization


Table 147. JVM_INFO view (continued)

System Column
Column Name Name Data Type Description

SHARED_CLASS_SIZE SHAREDSIZE BIGINT The amount of memory, in kilobytes, that the JVM is using for
shared classes.

BIT_MODE BIT_MODE INTEGER The Java version of this job.

32 32 bit Java job

64 64 bit Java job

Example
Examine the active JVM jobs, ordered by top heap space consumption.

SELECT * FROM QSYS2.JVM_INFO


ORDER BY CURRENT_HEAP_SIZE DESC

SET_JVM procedure
The SET_JVM procedure can be used to manage specific JVM jobs.
This actions provided by this Db2 for i procedure can also be accomplished interactively using the Work
with JVM Jobs (WRKJVMJOB) command.
Authorization: None required.

SET_JVM ( job_name , action )

The schema is QSYS2.

job_name A character or graphic string expression that identifies the qualified job name of the job to
change.
action A character or graphic string expression that specifies that action to perform. Supported
actions are:

GC_ENABLE_VERBOSE Enable verbose garbage collection detail.


GC_DISABLE_VERBOSE Disable verbose garbage collection detail.
GENERATE_HEAP_DUMP Generates information about the JVM's heap. Generates a
dump of all the heap space allocations which have not yet
been freed.
GENERATE_SYSTEM_DUMP Generates system detail for the JVM. Generates a binary
format raw memory image of the job that was running when
the dump was initiated.
GENERATE_JAVA_DUMP Generates Java detail for the JVM. Generates multiple files
that contain diagnostic information for the JVM and the Java
applications running within the JVM.

Example
• Change a specific web admin JVM to provide verbose garbage collection details:

CALL QSYS2.SET_JVM('121376/QWEBADMIN/ADMIN4','GC_ENABLE_VERBOSE') ;

Database performance and query optimization 653


Journal Services
These services provide information about audit journals and data journals.

ASSOCIATE_JOURNAL_RECEIVER table function


The ASSOCIATE_JOURNAL_RECEIVER table function associates one or more journal receivers with a
journal if the journal receiver was originally associated with the journal.
Authorization: The user must have:
• *EXECUTE authority to the library containing the journal receiver
• *OBJMGT authority to the journal receiver
• *EXECUTE authority to the library containing the journal
• *OBJMGT and *OBJOPR authority to the journal

ASSOCIATE_JOURNAL_RECEIVER ( journal-library
JOURNAL_LIBRARY =>

, journal-name ,
JOURNAL_NAME =>

receiver-library ,
RECEIVER_LIBRARY =>

receiver-name )
RECEIVER_NAME =>

The schema is QSYS2.

journal- A character or graphic string expression that identifies the library that contains journal-
library name. Can contain the special values *LIBL or *CURLIB.
journal-name A character or graphic string expression that identifies the name of the journal.
receiver- A character or graphic string expression that identifies the name of the library containing
library receiver-name. Can contain the special values *LIBL or *CURLIB.
receiver- A character or graphic string expression that identifies the name of the journal receiver.
name A generic name can be specified to select specific journal receivers. If the last character
in the name is an asterisk, the name is a generic name. For example, to select all journal
receivers that start with 'JR', specify a receiver-name value of 'JR*'.
The special value of *ALL can be used to select all journal receivers in receiver-library.
*ALL is not allowed if receiver-library is *LIBL.

The result of the function is a table containing rows with the format shown in the following table. All
columns are nullable.
Table 148. ASSOCIATE_JOURNAL_RECEIVER table function

Column name Data type Description

JOURNAL_LIBRARY VARCHAR(10) The library containing the journal that the journal receiver
attempted to associate with.

JOURNAL_NAME VARCHAR(10) The journal that the journal receiver attempted to associate
with.

RECEIVER_LIBRARY VARCHAR(10) The library containing the journal receiver.

RECEIVER_NAME VARCHAR(10) The journal receiver.

654 IBM i: Performance and Query Optimization


Table 148. ASSOCIATE_JOURNAL_RECEIVER table function (continued)

Column name Data type Description

RESULT VARCHAR(7) Result type.

FAILURE The operation did not complete.

SUCCESS The operation completed successfully.

WARNING The operation completed but a warning was


issued.

RESULT_DETAIL VARGRAPHIC(100) Descriptive text that corresponds to RESULT.

CCSID 1200

Database performance and query optimization 655


Table 148. ASSOCIATE_JOURNAL_RECEIVER table function (continued)

Column name Data type Description

RETURN_CODE INTEGER The return code that corresponds to the result.

0 The specified journal receiver was successfully


associated with the specified journal.

1 The specified journal receiver was already associated


with the specified journal.

2 The specified journal receiver could not be associated


with the specified journal because the journal receiver
was already associated with a different journal.

3 The specified journal receiver could not be associated


with the specified journal because the journal receiver
was never associated with that journal or could not be
associated with that journal in a remote journal network.

4 The specified journal receiver could not be associated


with the specified journal because the journal receiver’s
library could not be found.

5 The specified journal receiver could not be associated


with the specified journal because the journal receiver
could not be found.

6 The specified journal receiver could not be associated


with the specified journal because the journal’s library
could not be found.

7 The specified journal receiver could not be associated


with the specified journal because the journal could not
be found.

8 The specified journal receiver could not be associated


with the specified journal because the journal receiver
could not be locked.

9 The specified journal receiver could not be associated


with the specified journal because the journal could not
be locked.

10 The specified journal receiver could not be associated


with the specified journal because the user is not
authorized to the journal receiver’s library.

11 The specified journal receiver could not be associated


with the specified journal because the user is not
authorized to the journal receiver.

12 The specified journal receiver could not be associated


with the specified journal because the user is not
authorized to the journal’s library.

13 The specified journal receiver could not be associated


with the specified journal because the user is not
authorized to the journal.

14 The specified journal receiver could not be associated


with the specified journal because the journal receiver is
damaged.

15 The specified journal receiver could not be associated


with the specified journal because the journal is
damaged.

16 The specified journal receiver could not be associated


with the specified journal because the journal receiver
and journal are not both in the system or user auxiliary
storage pools (ASPs) or the journal receiver and journal
are in different independent auxiliary storage pool
(IASP) groups.

Example
Re-establish the association of journal APPLIB/APPJRN with journal receiver RCVRLIB/RCV001.

SELECT *
FROM TABLE(QSYS2.ASSOCIATE_JOURNAL_RECEIVER('APPLIB', 'APPJRN', 'RCVRLIB', 'RCV001'));

656 IBM i: Performance and Query Optimization


AUDIT_JOURNAL_DATA_MART_INFO view
The AUDIT_JOURNAL_DATA_MART_INFO view contains information about the AUDIT_JOURNAL_xx
data mart tables that are populated and updated using the MANAGE_AUDIT_JOURNAL_DATA_MART
procedure.
Authorization: The caller must have *AUDIT special authority.
The following table describes the columns in the view. There is one row of information for each audit
journal entry type that has been requested for each library. The system name is AJ_DMART. The schema
is QSYS2.
Table 149. AUDIT_JOURNAL_DATA_MART_INFO view

Column Name System Column Name Data Type Description

DATA_MART_LIBRARY LIBRARY VARCHAR(10) The library containing the data mart


table.

DATA_MART_TABLE TABLE CHAR(16) The name of the data mart table.

DATA_MART_SYSTEM_TABLE_NAME SYS_TABLE CHAR(5) The system name of the data mart


table.

JOURNAL_ENTRY_TYPE ENTRY CHAR(2) The journal entry type contained


within the data mart table.

AUDIT_JOURNAL_STARTING_TIMESTAM AJ_START TIMESTAMP The STARTING_TIMESTAMP


P parameter value for the most recent
call to the
MANAGE_AUDIT_JOURNAL_DATA_M
ART procedure for this
JOURNAL_ENTRY_TYPE and
DATA_MART_LIBRARY.

AUDIT_JOURNAL_ENDING_TIMESTAMP AJ_END TIMESTAMP The ENDING_TIMESTAMP parameter


value for the most recent call to the
MANAGE_AUDIT_JOURNAL_DATA_M
ART procedure for this
JOURNAL_ENTRY_TYPE and
DATA_MART_LIBRARY.

BUILD_START B_START TIMESTAMP The timestamp of the most recent call


to the
MANAGE_AUDIT_JOURNAL_DATA_M
ART procedure for this
JOURNAL_ENTRY_TYPE and
DATA_MART_LIBRARY.

BUILD_END B_END TIMESTAMP The timestamp of when the most


recent call to the
Nullable MANAGE_AUDIT_JOURNAL_DATA_M
ART procedure finished for this
JOURNAL_ENTRY_TYPE and
DATA_MART_LIBRARY.
Contains the null value if the
MANAGE_AUDIT_JOURNAL_DATA_M
ART procedure is running or if a
failure occurred during the call.

BUILD_JOB BUILD_JOB VARCHAR(28) The qualified job name that most


recently called the
MANAGE_AUDIT_JOURNAL_DATA_M
ART procedure for this
JOURNAL_ENTRY_TYPE and
DATA_MART_LIBRARY.

FAILURE_DETAIL FAILURE VARCHAR(300) The failure information for the most


recent call to the
Nullable MANAGE_AUDIT_JOURNAL_DATA_M
ART procedure for this
JOURNAL_ENTRY_TYPE and
DATA_MART_LIBRARY.
Contains the null value if no failure
occurred.

Examples

Database performance and query optimization 657


• Check for failures after calling the MANAGE_AUDIT_JOURNAL_DATA_MART procedure for the PW
journal entry in the library DMARTLIB.

SELECT DATA_MART_LIBRARY, DATA_MART_TABLE, JOURNAL_ENTRY_TYPE, BUILD_END, FAILURE_DETAIL


FROM QSYS2.AUDIT_JOURNAL_DATA_MART_INFO
WHERE JOURNAL_ENTRY_TYPE = 'PW' AND DATA_MART_LIBRARY = 'DMARTLIB'
AND FAILURE_DETAIL IS NOT NULL;

Audit journal entry services


These table functions provide detailed information for audit journal entries.

AUDIT JOURNAL table function common information


Each of the AUDIT_JOURNAL_xx table functions returns information from the audit journal specific to an
individual entry type. The invocation of every function and the first set of columns returned by the function
are identical. This common information is described in this section.
Authorization: The caller must have:
• *USE authority to the audit journal and to all requested journal receivers, and
• *OBJEXIST authority to the audit journal

658 IBM i: Performance and Query Optimization


AUDIT_JOURNAL_xx (

starting-receiver-name
STARTING_RECEIVER_NAME =>

, ending-receiver-name
ENDING_RECEIVER_NAME =>

, starting-timestamp
STARTING_TIMESTAMP =>

, ending-timestamp
ENDING_TIMESTAMP =>

, user-name
USER_NAME =>

, job , program
JOB => PROGRAM =>

, starting-sequence
STARTING_SEQUENCE =>

, ending-sequence
ENDING_SEQUENCE =>

starting-receiver-library
STARTING_RECEIVER_LIBRARY =>

)
, ending-receiver-library
ENDING_RECEIVER_LIBRARY =>

The schema is SYSTOOLS.


The function name, identified as AUDIT_JOURNAL_xx in the syntax diagram, represents any of the audit
journal functions. For example, to invoke the AUDIT_JOURNAL_PW function, replace the xx with PW.

starting- A character or graphic string expression that identifies the name of the starting journal
receiver-name receiver. The special values *CURRENT, *CURCHAIN, *CURAVLCHN, and *CURSEQCHN
are supported. Otherwise, starting-receiver-name must identify a valid journal receiver.
If no journal receiver is specified, *CURAVLCHN is used.

ending- A character or graphic string expression that identifies the name of the ending journal
receiver-name receiver. The special value *CURRENT is supported. Otherwise, ending-receiver-name
must identify a valid journal receiver.

Database performance and query optimization 659


If ending-receiver-name is not specified, *CURRENT is used.

starting- A timestamp value that specifies the starting timestamp to use1.


timestamp
A value cannot be specified for both starting-timestamp and starting-sequence.
If no starting timestamp is specified, CURRENT DATE - 1 DAY is used.

ending- A timestamp value that specifies the ending timestamp to use1.


timestamp
A value cannot be specified for both ending-timestamp and ending-sequence.
If no ending timestamp is specified, CURRENT TIMESTAMP is used.

user-name A character or graphic string expression that identifies the user profile name for the
current user of the job. If user-name is not specified, *ALL is used.
job A character or graphic string expression that identifies the name of a job. Two forms of a
job name are supported:
1. A fully qualified job name in the form job-number/job-user/job-name.
2. The first 10 characters are the job name, the second 10 characters are the user
name, and the last 6 characters are the job number.
If job is not specified, *ALL is used.
program A character or graphic string expression that identifies the name of a program. If
program is not specified, *ALL is used.
starting- A decimal expression that identifies the starting sequence number to use. This is
sequence the value shown in the SEQUENCE_NUMBER column in the QSYS2.DISPLAY_JOURNAL
results. If the starting-sequence value is not found in the receiver range, an error is
returned.
A value cannot be specified for both starting-timestamp and starting-sequence.
If no starting sequence is specified, *FIRST is used.

ending- A decimal expression that identifies the ending sequence number to use. If the ending-
sequence sequence value is not found in the receiver range, an error is returned.
A value cannot be specified for both ending-timestamp and ending-sequence.
If no ending sequence is specified, *LAST is used.
When ending-sequence is used, the query results will end when the first ending
sequence value is encountered. If the journal has had its sequence numbers reset,
ending-sequence will only return results through the first match of ending-sequence.

starting- A character or graphic string expression that identifies the library that contains starting-
receiver- receiver-name.
library
ending- A character or graphic string expression that identifies the library that contains ending-
receiver- receiver-name.
library

The special values supported for the function arguments are the same as for the Display Journal
(DSPJRN) CL command.

1 The accuracy of the entry timestamp stored in journal receivers is only accurate to 16 microseconds.
Hence, a value passed as a starting-timestamp and ending-timestamp will be truncated such that the
actual timestamps being searched for may be from 0 to 15 microseconds less than the specified value.

660 IBM i: Performance and Query Optimization


The first set of columns returned by each of the audit journal functions are information from the audit
journal entry's common header. They have the format shown in the following table. All the columns are
nullable.
Table 150. Common columns returned from the audit journal entry header

Column Name Data Type Description

ENTRY_TIMESTAMP TIMESTAMP The system date and time when the journal entry was added to the journal
receiver.

SEQUENCE_NUMBER DECIMAL(21,0) A number assigned by the system to each journal entry.

USER_NAME VARCHAR(10) The name of the effective user profile under which the thread was running
when the entry was created.
Contains *NONE if the effective user profile is not available.

QUALIFIED_JOB_NAME VARCHAR(28) The qualified job name that added the entry.
Contains the null value if the system job is running in a task rather than a
process.

JOB_NAME VARCHAR(10) The name of the job that added the entry.

JOB_USER VARCHAR(10) The user profile that started the job.


Contains the null value if the system job is running in a task rather than a
process.

JOB_NUMBER VARCHAR(6) The job number of the job that added the entry.
Contains the null value if the system job is running in a task rather than a
process.

THREAD BIGINT Identifies the thread within the process that added the journal entry.
Contains the null value if the system job is running in a task rather than a
process.

PROGRAM_LIBRARY VARCHAR(10) The name of the library that contains PROGRAM_NAME.


Contains *NONE if PROGRAM_NAME returns *NONE.

PROGRAM_NAME VARCHAR(10) The name of the program that caused the journal entry to be added. This
can also be the name of a service program or the partial name of a class file
used in a compiled Java program. If an application program or CL program
did not cause the entry, contains the name of a system-supplied program
such as QCMD.
Contains *NONE if one of the following conditions is true:
• The program name does not apply to this entry type.
• The program name was not available.

PROGRAM_LIBRARY_ASP_DEVICE VARCHAR(10) The name of the ASP device that contains PROGRAM_NAME.

PROGRAM_LIBRARY_ASP_NUMBER INTEGER The number for the auxiliary storage pool that contains PROGRAM_NAME.

REMOTE_PORT INTEGER The port number of the remote address associated with this journal entry.
Contains the null value if a remote port is not available.

REMOTE_ADDRESS VARCHAR(46) The remote address associated with the journal entry in IPv4 or IPv6
format.
Contains the null value if a remote address is not available.

SYSTEM_NAME VARCHAR(8) The name of the system on which the entry is being retrieved.

SYSTEM_SEQUENCE_NUMBER DECIMAL(21,0) The system sequence number which indicates the relative sequence of
when this journal entry was deposited into the journal.

RECEIVER_LIBRARY VARCHAR(10) The name of the library containing RECEIVER_NAME.

RECEIVER_NAME VARCHAR(10) The name of the receiver holding the journal entry.

RECEIVER_ASP_DEVICE VARCHAR(10) The name of the ASP device containing RECEIVER_NAME.

RECEIVER_ASP_NUMBER INTEGER The number for the auxiliary storage pool containing RECEIVER_NAME.

ARM_NUMBER INTEGER The number of the disk arm that contains the journal entry.

Database performance and query optimization 661


AUDIT_JOURNAL_AD table function
The AUDIT_JOURNAL_AD table function returns rows from the audit journal that contain information from
the AD (Auditing Change) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 151. AUDIT_JOURNAL_AD table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the AD audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

D CHGDLOAUD command

O CHGOBJAUD or CHGAUD command

S The scan attribute was changed using CHGATR command or


the Qp0lSetAttr API, or when the object was created.

U CHGUSRAUD command

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

OBJECT_AUDIT VARCHAR(10) The current object audit value.


Contains the null value if ENTRY_TYPE is S.

PREV_OBJECT_AUDIT VARCHAR(10) The previous object audit value.


Contains the null value if ENTRY_TYPE is S.

SCAN_ATTRIBUTE VARCHAR(10) The scan attribute value.


Contains the null value if ENTRY_TYPE is not S .

LIBRARY_NAME VARCHAR(10) Name of the library for the object.


Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) Name of the object for which auditing was changed.
Contains the null value if there is no object name.

OBJECT_TYPE VARCHAR(7) The type of object.


Contains the null value if there is no object type.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object
resides. A value of *SYSBAS indicates the system ASP and all basic
user ASPs.
Contains the null value if there is no ASP information.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.


Contains the null value if there is no ASP information.

PATH_NAME VARGRAPHIC(5000) CCSID 1200 The path name of the object.


Contains the null value if the path name is not available or the
object is not in the "root" (/), QOpenSys, or user-defined file
systems.

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator:

NO The PATH_NAME column does not contain an absolute path


name for the object, instead it contains a relative path
name. The RELATIVE_DIRECTORY_FILE_ID can be used to
form an absolute path name with this relative path name.

YES The PATH_NAME column contains the absolute path name


for the object.

Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

662 IBM i: Performance and Query Optimization


Table 151. AUDIT_JOURNAL_AD table function (continued)

Column Name Data Type Description

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the


directory that contains the object identified in the PATH_NAME
column.
Contains the null value when PATH_NAME_INDICATOR is YES, or
if the file ID is not available or the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) CCSID 1200 The name of the object.


Contains the null value if the object name is not available or
the object is not in the "root" (/), QOpenSys, or user-defined file
systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the object is
not in the "root" (/), QOpenSys, or user-defined file systems.

DLO_NAME VARCHAR(12) The name of the folder or document.


Contains the null value if there is no name or if ENTRY_TYPE is not
D.

FOLDER_PATH VARCHAR(63) The path of the folder.


Contains the null value if there is no folder path or if ENTRY_TYPE is
not D.

CHGUSRAUD_AUTFAIL VARCHAR(3) Write an audit record when this user has an authorization failure.

NO Do not write an audit record when this user has an


authorization failure.

YES Write an audit record when this user has an authorization


failure.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_CMD VARCHAR(3) Audit commands for this user.

NO Do not audit commands for this user.

YES Audit commands for this user.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_CREATE VARCHAR(3) Write an audit record when this user creates an object.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_DELETE VARCHAR(3) Write an audit record when this user deletes an object.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_JOBBAS VARCHAR(3) Write an audit record when this user performs a job base function.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

Database performance and query optimization 663


Table 151. AUDIT_JOURNAL_AD table function (continued)

Column Name Data Type Description

CHGUSRAUD_JOBCHGUSR VARCHAR(3) Write an audit record when this user changes a thread's active user
profile or its group file.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_JOBDTA VARCHAR(3) Write an audit record when this user changes a job.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_NETBAS VARCHAR(3) Write an audit record when this user performs network base
functions.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_NETCLU VARCHAR(3) Write an audit record when this user performs cluster or cluster
resource group functions.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_NETCMN VARCHAR(3) Write an audit record when this user performs network
communications functions.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_NETFAIL VARCHAR(3) Write an audit record when this user has a network failure.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_NETSCK VARCHAR(3) Write an audit record when this user performs sockets tasks.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_NETSECURE VARCHAR(3) Write an audit record when this user establishes a secure
connection.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_NETUDP VARCHAR(3) Write an audit record for UDP inbound and outbound traffic for this
user.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

664 IBM i: Performance and Query Optimization


Table 151. AUDIT_JOURNAL_AD table function (continued)

Column Name Data Type Description

CHGUSRAUD_OBJMGT VARCHAR(3) Write an audit record when this user moves or renames an object.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_OFCSRV VARCHAR(3) Write an audit record when this user performs office functions.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_OPTICAL VARCHAR(3) Write an audit record when this user accesses optical devices.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_PGMADP VARCHAR(3) Write an audit record when this user obtains authority through
adopted authority.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_PGMFAIL VARCHAR(3) Write an audit record when this user has a program failure.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_PRTDTA VARCHAR(3) Write an audit record when this user performs a print function with
parameter SPOOL(*NO).

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_SAVRST VARCHAR(3) Write an audit record when this user saves or restores objects.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_SECCFG VARCHAR(3) Write an audit record when this user performs security
configuration.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_SECDIRSRV VARCHAR(3) Write an audit record when this user makes changes or updates
using directory service functions.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

Database performance and query optimization 665


Table 151. AUDIT_JOURNAL_AD table function (continued)

Column Name Data Type Description

CHGUSRAUD_SECIPC VARCHAR(3) Write an audit record when this user makes changes to interprocess
communications.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_SECNAS VARCHAR(3) Write an audit record when this user performs network
authentication service actions.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_SECRUN VARCHAR(3) Write an audit record when this user performs security run time
functions.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_SECSCKD VARCHAR(3) Write an audit record when this user performs socket descriptor
functions.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_SECURITY VARCHAR(3) Write an audit record when this user performs security-relevant
actions.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_SECVFY VARCHAR(3) Write an audit record when this user uses verification functions.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_SECVLDL VARCHAR(3) Write an audit record when this user manipulates validation lists.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_SERVICE VARCHAR(3) Write an audit record when this user performs service functions.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

CHGUSRAUD_SPLFDTA VARCHAR(3) Write an audit record when this user manipulates spooled files.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

666 IBM i: Performance and Query Optimization


Table 151. AUDIT_JOURNAL_AD table function (continued)

Column Name Data Type Description

CHGUSRAUD_SYSMGT VARCHAR(3) Write an audit record when this user makes systems management
changes.

NO Do not write an audit record.

YES Write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_AUTFAIL VARCHAR(3) Previous value for write an audit record when this user has an
authorization failure.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_CMD VARCHAR(3) Previous value for audit commands for this user.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_CREATE VARCHAR(3) Previous value for write an audit record when this user creates an
object.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_DELETE VARCHAR(3) Previous value for write an audit record when this user deletes an
object.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_JOBBAS VARCHAR(3) Previous value for write an audit record when this user performs a
job base function.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_JOBCHGUSR VARCHAR(3) Previous value for write an audit record when this user changes a
thread's active user profile or its group file.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_JOBDTA VARCHAR(3) Previous value for write an audit record when this user changes a
job.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_NETBAS VARCHAR(3) Previous value for write an audit record when this user performs
network base functions.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

Database performance and query optimization 667


Table 151. AUDIT_JOURNAL_AD table function (continued)

Column Name Data Type Description

PREV_CHGUSRAUD_NETCLU VARCHAR(3) Previous value for write an audit record when this user performs
cluster or cluster resource group functions.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_NETCMN VARCHAR(3) Previous value for write an audit record when this user performs
network communications functions.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_NETFAIL VARCHAR(3) Previous value for write an audit record when this user has a
network failure.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_NETSCK VARCHAR(3) Previous value for write an audit record when this user performs
sockets tasks

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_NETSECURE VARCHAR(3) Previous value for write an audit record when this user establishes a
secure connection.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_NETUDP VARCHAR(3) Previous value for write an audit record for UDP inbound and
outbound traffic for this user.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_OBJMGT VARCHAR(3) Previous value for write an audit record when this user moves or
renames an object.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_OFCSRV VARCHAR(3) Previous value for write an audit record when this user performs
office functions.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_OPTICAL VARCHAR(3) Previous value for write an audit record when this user accesses
optical devices.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

668 IBM i: Performance and Query Optimization


Table 151. AUDIT_JOURNAL_AD table function (continued)

Column Name Data Type Description

PREV_CHGUSRAUD_PGMADP VARCHAR(3) Previous value for write an audit record when this user obtains
authority through adopted authority.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_PGMFAIL VARCHAR(3) Previous value for write an audit record when this user has a
program failure.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_PRTDTA VARCHAR(3) Previous value for write an audit record when this user performs a
print function with parameter SPOOL(*NO).

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SAVRST VARCHAR(3) Previous value for write an audit record when this user saves or
restores objects.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SECCFG VARCHAR(3) Previous value for write an audit record when this user performs
security configuration.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SECDIRSRV VARCHAR(3) Previous value for write an audit record when this user makes
changes or updates using directory service functions.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SECIPC VARCHAR(3) Previous value for write an audit record when this user makes
changes to interprocess communications.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SECNAS VARCHAR(3) Previous value for write an audit record when this user performs
network authentication service actions.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SECRUN VARCHAR(3) Previous value for write an audit record when this user performs
security run time functions.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

Database performance and query optimization 669


Table 151. AUDIT_JOURNAL_AD table function (continued)

Column Name Data Type Description

PREV_CHGUSRAUD_SECSCKD VARCHAR(3) Previous value for write an audit record when this user performs
socket descriptor functions.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SECURITY VARCHAR(3) Previous value for write an audit record when this user performs
security-relevant actions.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SECVFY VARCHAR(3) Previous value for write an audit record when this user uses
verification functions.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SECVLDL VARCHAR(3) Previous value for write an audit record when this user manipulates
validation lists.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SERVICE VARCHAR(3) Previous value for write an audit record when this user performs
service functions.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SPLFDTA VARCHAR(3) Previous value for write an audit record when this user manipulates
spooled files.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

PREV_CHGUSRAUD_SYSMGT VARCHAR(3) Previous value for write an audit record when this user makes
systems management changes.

NO Previous value was to not write an audit record.

YES Previous value was to write an audit record.

Contains the null value if ENTRY_TYPE is not U.

Example
• List objects in APPLIB that had auditing changes made with the CHGOBJAUD CL command yesterday
and today.

SELECT LIBRARY_NAME, OBJECT_NAME, OBJECT_TYPE , OBJECT_AUDIT


FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_AD (STARTING_TIMESTAMP => CURRENT DATE - 1 DAY)
)
WHERE ENTRY_TYPE = 'O' AND LIBRARY_NAME = 'APPLIB';

670 IBM i: Performance and Query Optimization


AUDIT_JOURNAL_AF table function
The AUDIT_JOURNAL_AF table function returns rows from the audit journal that contain information from
the AF (Authority Failure) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 152. AUDIT_JOURNAL_AF table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the AF audit journal entry.

VIOLATION_TYPE CHAR(1) The type of authority violation.

A Not authorized to object

B Restricted instruction

C Validation failure. See VALIDATION_ERROR_ACTION for additional


details.

D Use of unsupported interface, object domain failure

E Hardware storage protection error, program constant space violation

H Scan exit program action. See VALIDATION_ERROR_ACTION for


additional details.

I System Java inheritance not allowed

J Submit job profile error

K Special authority violation

N Profile token not a regenerable token

O Optical Object Authority Failure

P Profile swap error

R Hardware protection error

S Default sign-on attempt

T Not authorized to TCP/IP port

U User permission request not valid

V Profile token not valid for generating new profile token

W Profile token not valid for swap

X System violation. See OPERATION_VIOLATION_CODE for additional


details.

Y Not authorized to the current JUID field during a clear JUID operation.

Z Not authorized to the current JUID field during a set JUID operation.

VIOLATION_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the violation type.

Database performance and query optimization 671


Table 152. AUDIT_JOURNAL_AF table function (continued)

Column Name Data Type Description

VALIDATION_ERROR_ACTION CHAR(1) Action taken after validation error detected, set when VIOLATION_TYPE is C
or H.

A The translation of the object was not attempted or it failed. The


QALWOBJRST system value setting allowed the object to be restored.
The user doing the restore did not have *ALLOBJ special authority
and the system security level is set to 10, 20, or 30. Therefore, all
authorities to the object were retained.

B The translation of the object was not attempted or it failed. The


QALWOBJRST system value setting allowed the object to be restored.
The user doing the restore did not have *ALLOBJ special authority
and the system security level is set to 40 or above. Therefore, all
authorities to the object were revoked.

C The translation of the object was successful. The translated copy was
restored on the system.

D The translation of the object was not attempted or it failed. The


QALWOBJRST system value setting allowed the object to be restored.
The user doing the restore had *ALLOBJ special authority. Therefore,
all authorities to the object were retained.

E System install time error detected.

F The object was not restored because the signature is not IBM i format.

G Unsigned system or inherit state object found when checking system.

H Unsigned user state object found when checking system.

I Mismatch between object and its signature found when checking


system.

J IBM certificate not found when checking system.

K Invalid signature format found when checking system.

M Scan exit program modified the object that was scanned.

X Scan exit program wanted object marked as having a scan failure.

Contains the null value if VIOLATION_TYPE is not C or H.

VALIDATION_ERROR_ACTION_DETAIL VARCHAR(200) Descriptive text that corresponds to the violation error action.
Contains the null value if VIOLATION_TYPE is not C or H.

OPERATION_VIOLATION_CODE CHAR(3) The type of operation violation that occurred, set when VIOLATION_TYPE is
X.

AAC Not authorized to use SST Advanced Analysis Command.

HCA Service tool user profile not authorized to perform hardware


configuration operation (QYHCHCOP).

LIC LIC indicates that a Licensed Internal Code fix was not applied
because of a signature violation.

SFA Not authorized to activate the environment attribute for system file
access.

CMD An attempt was made to use a command that has been disabled by
a system administrator.

Contains the null value if the VIOLATION_TYPE is not X.

OBJECT_LIBRARY VARCHAR(10) The name of the library containing the object.


When VIOLATION_TYPE is K, contains the name of the program's library or
the command's library that detected the error.
Contains the null value if there is no library name.

672 IBM i: Performance and Query Optimization


Table 152. AUDIT_JOURNAL_AF table function (continued)

Column Name Data Type Description

OBJECT_NAME VARCHAR(10) The name of the object.


When VIOLATION_TYPE is K, contains the name of the command or
program that detected the error. If the command has several alternative
names, the command name in the audit record might not match the specific
command name used but will be one of the equivalent alternatives. A
special value of *INSTR indicates that a machine instruction detected the
error.
When OBJECT_TYPE is *LIC, contains a Licensed Internal Code replacement
unit (RU) name.
Contains the null value if there is no object name.

OBJECT_TYPE VARCHAR(7) The type of the object.


When VIOLATION_TYPE is K, contains the object type of the command or
program that detected the error.
When VIOLATION_TYPE is G, contains the name of the *SRVPGM that
contained the exit that detected the error.
Contains the null value if there is no object type.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object resides. A
value of *SYSBAS indicates the system ASP and all basic user ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.

FIELD_NAME VARCHAR(10) The system name of the column.


Contains the null value if the authority is not related to a column or the
column name is not available.

TCPIP_PORT INTEGER The TCP/IP port the user is not authorized to use, when VIOLATION_TYPE is
T.
Contains the null value if VIOLATION_TYPE is not T.

API_NAME VARCHAR(20) The full API name of the API or exit point name that detected the error,
when VIOLATION_TYPE is K.
Contains the null value when the VIOLATION_TYPE is not K or if there is no
API or exit point information.

PTF_NUMBER CHAR(7) The PTF number that failed to apply because of a signature violation when
the VIOLATION_TYPE is X and OPERATION_VIOLATION_CODE is LIC.
Contains the null value if VIOLATION_TYPE is not X with an
OPERATION_VIOLATION_CODE of LIC.

AAC_NAME VARCHAR(30) The Advanced Analysis Command name, when the VIOLATION_TYPE is X
and the OPERATION_VIOLATION_CODE is AAC.
Contains the null value if VIOLATION_TYPE is not X with an
OPERATION_VIOLATION_CODE of AAC.

USER_PROFILE_NAME VARCHAR(10) The name of the user that caused the authority failure.
Contains the null value if the user name is not available.

WORKSTATION_NAME VARCHAR(10) The name of the workstation or workstation type.


Contains the null value if the workstation name is not available.

PROGRAM_INSTRUCTION INTEGER The instruction number of the program.


Contains the null value if the instruction number is not available.

PATH_NAME VARGRAPHIC(5000) The path name of the object.


CCSID 1200
Contains the null value if the object name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path name


for the object, instead it contains a relative path name. The
RELATIVE_DIRECTORY_FILE_ID can be used to form an absolute
path name with this relative path name.

YES The PATH_NAME column contains complete absolute path name for
the object.

Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

Database performance and query optimization 673


Table 152. AUDIT_JOURNAL_AF table function (continued)

Column Name Data Type Description

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the directory
that contains the object identified in the PATH_NAME column.
Contains the null value when PATH_NAME_INDICATOR is YES, or if the
file ID is not available or the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) The name of the object.


CCSID 1200
Contains the null value if the object name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the object is not in the
"root" (/), QOpenSys, or user-defined file systems.

OFFICE_USER VARCHAR(10) The name of the office user.


Contains the null value if there is no office user.

OFFICE_ON_BEHALF_OF_USER VARCHAR(10) User working on behalf of another user.


Contains the null value if the user name is not available.

DLO_NAME VARCHAR(12) The name of the document library object.


Contains the null value if there is no document library object.

FOLDER_PATH VARCHAR(63) The path of the folder.


Contains the null value if there is no folder path.

Example
• Find any authority failures for Integrated File System (IFS) objects in the past 24 hours.

SELECT * FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_AF(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 1 DAY
)
) WHERE PATH_NAME IS NOT NULL;

• Determine the number of 'Not authorized to object' authority failures for user BOB in the last week.

SELECT COUNT(*) FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_AF(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS,
USER_NAME => 'BOB'
)
) WHERE VIOLATION_TYPE = 'A';

AUDIT_JOURNAL_AP table function


The AUDIT_JOURNAL_AP table function returns rows from the audit journal that contain information from
the AP (Adopted Authority) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 153. AUDIT_JOURNAL_AP table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the AP audit journal entry.

674 IBM i: Performance and Query Optimization


Table 153. AUDIT_JOURNAL_AP table function (continued)

Column Name Data Type Description

ENTRY_TYPE CHAR(1) The type of entry.

A Adopted authority used during program activation

E End

S Start

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

OBJECT_LIBRARY VARCHAR(10) The name of the library containing the program, service program, or SQL
package.

OBJECT_NAME VARCHAR(10) The name of the program, service program, or SQL package.

OBJECT_TYPE VARCHAR(7) The type of the object.

OBJECT_OWNER VARCHAR(10) The name of the user profile whose authority is adopted.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object resides. A
value of *SYSBAS indicates the system ASP and all basic user ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

Example
• Find any programs that used adopted authority today.

SELECT OBJECT_LIBRARY, OBJECT_NAME, OBJECT_TYPE, OBJECT_OWNER FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_AP(
STARTING_TIMESTAMP => CURRENT DATE
)
);

AUDIT_JOURNAL_AU table function


The AUDIT_JOURNAL_AU table function returns rows from the audit journal that contain information from
the AU (Attribute Changes) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 154. AUDIT_JOURNAL_AU table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the AU audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A EIM association

E EIM configuration attributes

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

Database performance and query optimization 675


Table 154. AUDIT_JOURNAL_AU table function (continued)

Column Name Data Type Description

ACTION VARCHAR(6) The action that was performed.


When ENTRY_TYPE is A:

ADD Add association

REMOVE Remove association

When ENTRY_TYPE is E:

CHANGE Attributes changed

ACTION_DETAIL VARCHAR(200) Descriptive text that corresponds to the action.

ATTRIBUTE_NAME VARCHAR(100) The name of the changed attribute.


Contains the null value if ENTRY_TYPE is A.

ATTRIBUTE_VALUE VARGRAPHIC(2000) The value of the attribute.


CCSID 1200
Contains the null value if ENTRY_TYPE is A.

PREV_ATTRIBUTE_VALUE VARGRAPHIC(2000) The previous value of the attribute.


CCSID 1200
Contains the null value if ENTRY_TYPE is A.

ASSOCIATION_TYPE VARCHAR(17) The association type that was added or removed:


• ADMINISTRATIVE
• ALL
• TARGET
• SOURCE AND TARGET
• SOURCE
Contains the null value if ENTRY_TYPE is E.

REGISTRY_USER_NAME VARCHAR(100) The registry user name.


Contains the null value if ENTRY_TYPE is E.

IDENTIFIER_DISTINGUISHED_NAME VARGRAPHIC(1000) The identifier distinguished name.


CCSID 1200
Contains the null value if ENTRY_TYPE is E.

REGISTRY_DISTINGUISHED_NAME VARGRAPHIC(1000) The registry distinguished name.


CCSID 1200
Contains the null value if ENTRY_TYPE is E.

Example
• List the EIM configuration attributes that were changed in the last two months.

SELECT * FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_AU(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 2 MONTHS
)
)
WHERE ENTRY_TYPE = 'E' AND ACTION = 'CHANGE';

AUDIT_JOURNAL_AX table function


The AUDIT_JOURNAL_AX table function returns rows from the audit journal that contain information from
the AX (Row and Column Access Control) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.

676 IBM i: Performance and Query Optimization


Table 155. AUDIT_JOURNAL_AX table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the AX audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

M Column mask

P Row permission

T Table

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

OPERATION_TYPE VARCHAR(8) The type of operation.

ALTER Alter

CREATE Create

DROP Drop

INTERNAL Internal use only

LIBRARY_NAME VARCHAR(10) The name or the library where the file is stored.

FILE_NAME VARCHAR(10) The system name of the base table that the permission or mask is
associated with or the table being altered.

MASK_NAME VARCHAR(128) The column mask name.


Contains the null value if ENTRY_TYPE is not M.

COLUMN_NAME VARCHAR(10) The name of the column to which the mask applies.
Contains the null value if ENTRY_TYPE is not M or
OPERATION_TYPE is not CREATE.

PERMISSION_NAME VARCHAR(128) The row permission name.


Contains the null value if ENTRY_TYPE is not P.

ENABLED VARCHAR(3) The row permission or column mask state.

NO The row permission or column mask is set to disabled.

YES The row permission or column mask is set to enabled.

Contains the null value if ENTRY_TYPE is not M or P or


OPERATION_TYPE is not CREATE or ALTER.

ROW_ACCESS_CONTROL VARCHAR(10) The row access control state.

ACTIVATE Row access control is set to activate.

DEACTIVATE Row access control is set to deactivate.

Contains the null value if ENTRY_TYPE is not T or OPERATION_TYPE


is not ALTER, or the value was not changed.

COLUMN_ACCESS_CONTROL VARCHAR(10) The column access control state.

ACTIVATE Column access control is set to activate.

DEACTIVATE Column access control is set to deactivate.

Contains the null value if ENTRY_TYPE is not T or OPERATION_TYPE


is not ALTER, or the value was not changed.

PREV_ENABLED VARCHAR(3) The previous row permission or column mask state.

NO The row permission or column mask is set to disabled.

YES The row permission or column mask is set to enabled.

Contains the null value if ENTRY_TYPE is not M or P or


OPERATION_TYPE is not ALTER.

Database performance and query optimization 677


Table 155. AUDIT_JOURNAL_AX table function (continued)

Column Name Data Type Description

PREV_ROW_ACCESS_CONTROL VARCHAR(10) The previous row access control state.

ACTIVATE Row access control is set to activate.

DEACTIVATE Row access control is set to deactivate.

Contains the null value if ENTRY_TYPE is not T or OPERATION_TYPE


is not ALTER, or the value was not changed.

PREV_COLUMN_ACCESS_CONTROL VARCHAR(10) The previous column access control state.

ACTIVATE Column access control is set to activate.

DEACTIVATE Column access control is set to deactivate.

Contains the null value if ENTRY_TYPE is not T or OPERATION_TYPE


is not ALTER, or the value was not changed.

SQL_STATEMENT_TEXT VARGRAPHIC(5000) CCSID 1200 The SQL statement text for the CREATE MASK or CREATE
PERMISSION statement.
Contains the null value if ENTRY_TYPE is not M or P or
OPERATION_TYPE is not CREATE.

STATEMENT_TRUNCATED VARCHAR(3) Whether SQL_STATEMENT_TEXT is truncated.

NO SQL_STATEMENT contains the complete statement text.

YES SQL_STATEMENT contains truncated statement text.

Contains the null value if ENTRY_TYPE is not M or P or


OPERATION_TYPE is not CREATE.

ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object
resides. A value of *SYSBAS indicates the system ASP and all basic
user ASPs.
Contains the null value if there is no ASP information.

ASP_NUMBER INTEGER The number of the ASP device.


Contains the null value if there is no ASP information.

Example
• List any changes to active row or column access control for the last week. These are operations
performed by an ALTER TABLE statement with an ACTIVATE or DEACTIVATE option.

SELECT LIBRARY_NAME, FILE_NAME, ROW_ACCESS_CONTROL, COLUMN_ACCESS_CONTROL,


PREV_ROW_ACCESS_CONTROL, PREV_COLUMN_ACCESS_CONTROL
FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_AX (STARTING_TIMESTAMP => CURRENT DATE - 7 DAYS)
)
WHERE ENTRY_TYPE = 'T';

AUDIT_JOURNAL_CA table function


The AUDIT_JOURNAL_CA table function returns rows from the audit journal that contain information from
the CA (Authority Changes) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 156. AUDIT_JOURNAL_CA table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the CA audit journal entry.

678 IBM i: Performance and Query Optimization


Table 156. AUDIT_JOURNAL_CA table function (continued)

Column Name Data Type Description

OBJECT_LIBRARY VARCHAR(10) The name of the library containing the object.


Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) The name of the object.


Contains the null value if there is no object name.

OBJECT_TYPE VARCHAR(7) The type of the object.


Contains the null value if there is no object type.

OBJECT_ATTRIBUTE VARCHAR(10) The attribute for the object type.


Contains the null value if there is no object attribute.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which OBJECT_NAME
resides. A value of *SYSBAS indicates the system ASP and all basic user
ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the auxiliary storage pool to which storage for
OBJECT_NAME is allocated.

FIELD_NAME VARCHAR(10) The system name of the column.


Contains the null value if the authority is not related to a column or the
column name is not available.

COMMAND_TYPE VARCHAR(9) The type of command used.

GRANT Grant

GRTUSRAUT GRTUSRAUT operation

REPLACE Grant with replace

REVOKE Revoke

USER_PROFILE_NAME VARCHAR(10) The name of the user profile whose authority is being granted or revoked.
Contains the null value if a user profile is not being changed.

AUTHORIZATION_LIST_MANAGEMENT VARCHAR(3) Indicates whether authorization list management (*AUTLMGT) authority is


granted or revoked.

NO The authority is not changed.

YES The authority might have changed.

OBJECT_EXCLUDE VARCHAR(3) Indicates whether exclude (*EXCLUDE) authority is granted or revoked.

NO The authority is not changed.

YES The authority might have changed.

OBJECT_OPERATIONAL VARCHAR(3) Indicates whether object operational (*OBJOPR) authority is granted or


revoked.

NO The authority is not changed.

YES The authority might have changed.

OBJECT_MANAGEMENT VARCHAR(3) Indicates whether object management (*OBJMGT) authority is granted or


revoked.

NO The authority is not changed.

YES The authority might have changed.

OBJECT_EXISTENCE VARCHAR(3) Indicates whether object existence (*OBJEXIST) authority is granted or


revoked.

NO The authority is not changed.

YES The authority might have changed.

OBJECT_ALTER VARCHAR(3) Indicates whether object alter (*OBJALTER) authority is granted or revoked.

NO The authority is not changed.

YES The authority might have changed.

Database performance and query optimization 679


Table 156. AUDIT_JOURNAL_CA table function (continued)

Column Name Data Type Description

OBJECT_REFERENCE VARCHAR(3) Indicates whether object reference (*OBJREF) authority is granted or


revoked.

NO The authority is not changed.

YES The authority might have changed.

DATA_READ VARCHAR(3) Indicates whether data read (*READ) authority is granted or revoked.

NO The authority is not changed.

YES The authority might have changed.

DATA_ADD VARCHAR(3) Indicates whether data add (*ADD) authority is granted or revoked.

NO The authority is not changed.

YES The authority might have changed.

DATA_UPDATE VARCHAR(3) Indicates whether data update (*UPD) authority is granted or revoked.

NO The authority is not changed.

YES The authority might have changed.

DATA_DELETE VARCHAR(3) Indicates whether data delete (*DLT) authority is granted or revoked.

NO The authority is not changed.

YES The authority might have changed.

DATA_EXECUTE VARCHAR(3) Indicates whether data execute (*EXECUTE) authority is granted or revoked.

NO The authority is not changed.

YES The authority might have changed.

PREV_AUTHORIZATION_LIST_MANAGEMEN VARCHAR(3) Indicates whether the user previously had authorization list management
T (*AUTLMGT) authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the AUTHORIZATION_LIST_MANAGEMENT


column is NO.

PREV_OBJECT_EXCLUDE VARCHAR(3) Indicates whether the user previously had exclude (*EXCLUDE) authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the OBJECT_EXCLUDE column is NO.

PREV_OBJECT_OPERATIONAL VARCHAR(3) Indicates whether the user previously had object operational (*OBJOPR)
authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the OBJECT_OPERATIONAL column is NO.

PREV_OBJECT_MANAGEMENT VARCHAR(3) Indicates whether the user previously had object management (*OBJMGT)
authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the OBJECT_MANAGEMENT column is NO.

680 IBM i: Performance and Query Optimization


Table 156. AUDIT_JOURNAL_CA table function (continued)

Column Name Data Type Description

PREV_OBJECT_EXISTENCE VARCHAR(3) Indicates whether the user previously had object existence (*OBJEXIST)
authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the OBJECT_EXISTENCE column is NO.

PREV_OBJECT_ALTER VARCHAR(3) Indicates whether the user previously had object alter (*OBJALTER)
authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the OBJECT_ALTER column is NO.

PREV_OBJECT_REFERENCE VARCHAR(3) Indicates whether the user previously had object reference (*OBJREF)
authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the OBJECT_REFERENCE column is NO.

PREV_DATA_READ VARCHAR(3) Indicates whether the user previously had data read (*READ) authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the DATA_READ column is NO.

PREV_DATA_ADD VARCHAR(3) Indicates whether the user previously had data add (*ADD) authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the DATA_ADD column is NO.

PREV_DATA_UPDATE VARCHAR(3) Indicates whether the user previously had data update (*UPD) authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the DATA_UPDATE column is NO.

PREV_DATA_DELETE VARCHAR(3) Indicates whether the user previously had data delete (*DLT) authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the DATA_DELETE column is NO.

PREV_DATA_EXECUTE VARCHAR(3) Indicates whether the user previously had data execute (*EXECUTE)
authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the DATA_EXECUTE column is NO.

AUTHORIZATION_LIST VARCHAR(10) The name of the authorization list that is being modified.
Contains the null value if an authorization list is not being changed.

AUTHORIZATION_LIST_PUBLIC VARCHAR(3) Indicates whether authorization list (*AUTL public authority) authority has
been granted or revoked.

NO The authority is not changed.

YES The authority might have changed.

PREV_AUTHORIZATION_LIST VARCHAR(10) The name of the previous authorization list.


Contains the null value if an authorization list is not being changed.

Database performance and query optimization 681


Table 156. AUDIT_JOURNAL_CA table function (continued)

Column Name Data Type Description

PREV_AUTHORIZATION_LIST_PUBLIC VARCHAR(3) Indicates whether the user previously had authorization list (*AUTL public
authority) authority.

NO The user did not have this authority.

YES The user had this authority.

Contains the null value if the AUTHORIZATION_LIST_PUBLIC column is NO.

PERSONAL_STATUS_CHANGED VARCHAR(3) The personal status changed.

NO The status did not changed.

YES The status changed.

ACCESS_CODE_CHANGED VARCHAR(6) Whether the access code changed.

ADD The access code was added.

REMOVE The access code was removed.

Contains the null value if the access code was not changed.

ACCESS_CODE VARCHAR(4) Access code.


Contains the null value if the access code was not changed.

PATH_NAME VARGRAPHIC(5000) The path name of the object.


CCSID 1200
Contains the null value if the object name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path name


for the object, instead it contains a relative path name. The
RELATIVE_DIRECTORY_FILE_ID can be used to form an absolute
path name with this relative path name.

YES The PATH_NAME column contains complete absolute path name for
the object.

Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the directory
that contains the object identified in the PATH_NAME column.
Contains the null value when PATH_NAME_INDICATOR is YES, or if the
file ID is not available or the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) The name of the object.


CCSID 1200
Contains the null value if the object name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the object is not in the
"root" (/), QOpenSys, or user-defined file systems.

OFFICE_USER VARCHAR(10) The name of the office user.


Contains the null value if there is no office user.

OFFICE_ON_BEHALF_OF_USER VARCHAR(10) User working on behalf of another user.


Contains the null value if the user name is not available.

DLO_NAME VARCHAR(12) The name of the document library object.


Contains the null value if there is no document library object.

FOLDER_PATH VARCHAR(63) The path of the folder.


Contains the null value if there is no folder path.

682 IBM i: Performance and Query Optimization


Example
• List any files in APPLIB1 that had the ability to change data granted to them in the last week.

SELECT OBJECT_NAME, USER_PROFILE_NAME FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_CA(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS)
)
WHERE COMMAND_TYPE = 'GRANT' AND
OBJECT_LIBRARY = 'APPLIB1' AND
OBJECT_TYPE = '*FILE' AND
(DATA_ADD = 'YES' OR DATA_UPDATE = 'YES' OR DATA_DELETE = 'YES');

AUDIT_JOURNAL_CD table function


The AUDIT_JOURNAL_CD table function returns rows from the audit journal that contain information from
the CD (Command String) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 157. AUDIT_JOURNAL_CD table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the CD audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

C Command run

L OCL statement

O Operator control command

P S/36 procedure

S Command run after command substitution took place

U Utility control statement

X Proxy command

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

OBJECT_LIBRARY VARCHAR(10) The name of the library where the object is stored.

OBJECT_NAME VARCHAR(10) The name of the object.

OBJECT_TYPE VARCHAR(7) The type of object.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object resides. A
value of *SYSBAS indicates the system ASP and all basic user ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.

WHERE_RUN CHAR(1) Where the CL command was run.

B In a batch job but not for any of the reason listed under Y, R, or E.
Typical case would be that the CL command was run using STRDBRDR
or SBMDBJOB command or was specified on the CMD parameter of
the SBMJOB command.

E The command string was passed as a parameter to one of the


Command Analyzer APIs: QCMDEXC, QCAPCMD, or QCAEXEC

N Interactively from a command line or by choosing a menu option that


runs a CL command

R From a REXX procedure

Y From a compiled OPM CL program or an ILE CL program

WHERE_RUN_DETAIL VARCHAR(200) Descriptive text that corresponds to where the CL command was run.

Database performance and query optimization 683


Table 157. AUDIT_JOURNAL_CD table function (continued)

Column Name Data Type Description

COMMAND_STRING VARCHAR(6000) The command that was run, with parameters.


Contains the null value if no command was run.

Example
• List any change commands that were run this week.

SELECT *
FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_CD (STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS)
)
WHERE ENTRY_TYPE = 'C' AND
OBJECT_LIBRARY = 'QSYS' AND
OBJECT_NAME LIKE 'CHG%' ;

AUDIT_JOURNAL_CO table function


The AUDIT_JOURNAL_CO table function returns rows from the audit journal that contain information from
the CO (Create Object) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 158. AUDIT_JOURNAL_CO table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the CO audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

N Create of new object

R Replacement of existing object

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

OBJECT_LIBRARY VARCHAR(10) The name of the library containing the object.


Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) The name of the object.


Contains the null value if there is no object name.

OBJECT_TYPE VARCHAR(7) The type of the object.


Contains the null value if there is no object type.

OBJECT_ATTRIBUTE VARCHAR(10) The attribute for the object type.


Contains the null value if there is no object attribute.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object resides. A
value of *SYSBAS indicates the system ASP and all basic user ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.

PATH_NAME VARGRAPHIC(5000) The path name of the object.


CCSID 1200
Contains the null value if the path name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

684 IBM i: Performance and Query Optimization


Table 158. AUDIT_JOURNAL_CO table function (continued)

Column Name Data Type Description

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path name


for the object, instead it contains a relative path name. The
RELATIVE_DIRECTORY_FILE_ID can be used to form an absolute
path name with this relative path name.

YES The PATH_NAME column contains complete absolute path name for
the object.

Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the directory
that contains the object identified in the PATH_NAME column.
Contains the null value when PATH_NAME_INDICATOR is YES, or if the
file ID is not available or the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) The name of the object.


CCSID 1200
Contains the null value if the object name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the object is not in the
"root" (/), QOpenSys, or user-defined file systems.

OFFICE_USER VARCHAR(10) The name of the office user.


Contains the null value if there is no office user.

OFFICE_ON_BEHALF_OF_USER VARCHAR(10) User working on behalf of another user.


Contains the null value if the user name is not available.

DLO_NAME VARCHAR(12) The name of the document library object.


Contains the null value if there is no document library object.

FOLDER_PATH VARCHAR(63) The path of the folder.


Contains the null value if there is no folder path.

Example
• Find the objects created in APPLIB in the last 2 months.

SELECT OBJECT_LIBRARY, OBJECT_NAME, OBJECT_TYPE FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_CO(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 2 MONTHS
)
) WHERE OBJECT_LIBRARY = 'APPLIB';

AUDIT_JOURNAL_CP table function


The AUDIT_JOURNAL_CP table function returns rows from the audit journal that contain information from
the CP (User Profile Changes) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.

Database performance and query optimization 685


Table 159. AUDIT_JOURNAL_CP table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the CP audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Change to a user profile

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

USER_PROFILE VARCHAR(10) The user profile that was changed.

COMMAND_TYPE CHAR(3) The type of command used.

CHG Change User Profile (CHGUSRPRF) or Change Expiration Scd Entry


(CHGEXPSCDE) commands

CRT Create User Profile (CRTUSRPRF) command

DST QSECOFR password reset using DST

RPA Reset Profile Attributes (QSYRESPA) API

RST Restore User Profile (RSTUSRPRF) command

SQL QSYS2/SET_SERVER_SBS_ROUTING() Db2® for i procedure

STATUS VARCHAR(9) User profile status.

*DISABLED The user profile cannot be used

*ENABLED The user profile is valid

Contains the null value if the value was not changed.

PASSWORD_CHANGED VARCHAR(3) Whether the password changed.

YES Password changed

Contains the null value if the value was not changed.

NO_PASSWORD_INDICATOR VARCHAR(3) Whether the password is *NONE.

YES Password is *NONE

Contains the null value if the value was not changed.

PASSWORD_EXPIRED VARCHAR(4) Whether the password is expired.

*NO Password is not expired

*YES Password is expired

Contains the null value if the value was not changed.

LOCAL_PASSWORD_MANAGEMENT VARCHAR(4) Specifies whether the user profile password should be managed locally.

*NO The password is not managed on the local system.

*YES The password is managed on the local system.

Contains the null value if the value was not changed.

PASSWORD_CONFORMANCE VARCHAR(8) Indicates whether the new password conforms to the password
composition rules.

*EXITPGM Checked but does not conform because of an exit program


response.

*NOCHECK Not checked; password was changed.

*NONE Not checked; *NONE was specified for the new password.

*PASSED Checked and conforms.

*SYSVAL Checked but does not conform because of a system value


based rule.

Contains the null value if PASSWORD_CHANGED is not YES.

686 IBM i: Performance and Query Optimization


Table 159. AUDIT_JOURNAL_CP table function (continued)

Column Name Data Type Description

BLOCK_PASSWORD_CHANGE VARCHAR(7) Specifies the value that the block password change has been changed to.

1-99 Blocked hours.

*NONE No block period.

*SYSVAL The system value QPWDCHGBLK is used.

Contains the null value if the value was not changed.

PASSWORD_EXPIRATION_INTERVAL VARCHAR(7) Specifies the value that the password expiration interval has been changed
to.

1-366 The size of the expiration interval in days.

*NOMAX No expiration interval.

*SYSVAL The system value QPWDEXPITV is used.

Contains the null value if the value was not changed.

USER_EXPIRATION_DATE VARCHAR(10) Specifies the date when the user profile expires. The user profile is
automatically disabled or deleted on this date. Can contain the special value
*NONE to indicate the user profile does not expire.
Contains the null value if the value was not changed.

USER_EXPIRATION_ACTION CHAR(3) The action performed on the profile when it expires. This value is always
DSB when using the CRTUSRPRF and CHGUSRPRF commands. When using
the CHGEXPSCDE command, this value is one of the following values.

DLT The profile is deleted when it expires.

DSB The profile is disabled when it expires.

Contains the null value if the value was not changed.

OWNED_OBJECT_OPTION VARCHAR(7) The type of operation performed on the objects owned by the expiring
profile. The owned object option value is specified on the OWNOBJOPT
parameter of the CHGEXPSCDE ACTION(*DELETE) command.

*CHGOWN The owned objects for the user profile have ownership
transferred to the new owner user profile. The user profile
is deleted if the transfer of all owned objects is successful.

*DLT The owned objects for the user profile are deleted. The
user profile is deleted if the deletion of all owned objects
is successful.

*NODLT The owned objects for the user profile are not changed, and
the user profile is not deleted if the user owns any objects.

Contains the null value if USER_EXPIRATION_ACTION is not DLT or if the


value was not changed.

OWNED_OBJECT_OPTION_NEW_OWNER VARCHAR(10) The profile that will own all of the objects owned by the expiring profile.
Contains the null value if OWNED_OBJECT_OPTION is not *CHGOWN or if
the value was not changed.

PRIMARY_GROUP_OPTION VARCHAR(7) The type of operation performed on the objects that have the expiring
user profile as their primary group. The primary group option value is
specified on the PGPOPT parameter of the CHGEXPSCDE ACTION(*DELETE)
command.

*CHGPGP The objects the user profile is the primary group for are
transferred to the new primary group user profile. The user
profile is deleted if the transfer of all objects is successful.

*NOCHG The objects the user profile is the primary group for do not
change, and the user profile is not deleted if the user is the
primary group for any objects.

Contains the null value if USER_EXPIRATION_ACTION is not DLT or if the


value was not changed.

Database performance and query optimization 687


Table 159. AUDIT_JOURNAL_CP table function (continued)

Column Name Data Type Description

NEW_PRIMARY_GROUP VARCHAR(10) The profile that will become the new primary group of the objects for which
the expiring profile is the primary group. Can contain the following special
value:

*NONE All of the objects for which the expiring user is the primary group
will no longer have a primary group.

Contains the null value when PRIMARY_GROUP_OPTION is not *CHGPGP or


if the value was not changed.

NEW_PRIMARY_GROUP_AUTHORITY VARCHAR(8) The authority the new primary group has to the object.

*ALL The new primary group has *ALL authority to the object.

*CHANGE The new primary group has *CHANGE authority to the object.

*EXCLUDE The new primary group has *EXCLUDE authority to the


object.

*OLDPGP The new primary group has the same authority to the object
as the old primary group.

*PRIVATE The new primary group has the same authority to the object
as its private authority to the object was.

*USE The new primary group has *USE authority to the object.

Contains the null value when PRIMARY_GROUP_OPTION is not *CHGPGP or


NEW_PRIMARY_GROUP is *NONE or if the value was not changed.

USER_CLASS_NAME VARCHAR(7) The user class of the user.

*PGMR Programmer

*SECADM Security administrator

*SECOFR Security officer

*SYSOPR System operator

*USER User

Contains the null value if the value was not changed.

SPECIAL_AUTHORITIES VARCHAR(72) Current list of special authorities. This is a single string containing the list of
special authorities separated by one blank.
Contains the null value if the value was not changed.

ALLOBJ VARCHAR(3) Current *ALLOBJ special authority

YES Profile has *ALLOBJ special authority

Contains the null value if the value was not changed.

JOBCTL VARCHAR(3) Current *JOBCTL special authority

YES Profile has *JOBCTL special authority

Contains the null value if the value was not changed.

SAVSYS VARCHAR(3) Current *SAVSYS special authority

YES Profile has *SAVSYS special authority

Contains the null value if the value was not changed.

SECADM VARCHAR(3) Current *SECADM special authority

YES Profile has *SECADM special authority

Contains the null value if the value was not changed.

SPLCTL VARCHAR(3) Current *SPLCTL special authority

YES Profile has *SPLCTL special authority

Contains the null value if the value was not changed.

688 IBM i: Performance and Query Optimization


Table 159. AUDIT_JOURNAL_CP table function (continued)

Column Name Data Type Description

SERVICE VARCHAR(3) Current *SERVICE special authority

YES Profile has *SERVICE special authority

Contains the null value if the value was not changed.

AUDIT VARCHAR(3) Current *AUDIT special authority

YES Profile has *AUDIT special authority

Contains the null value if the value was not changed.

IOSYSCFG VARCHAR(3) Current *IOSYSCFG special authority

YES Profile has *IOSYSCFG special authority

Contains the null value if the value was not changed.

PREVIOUS_SPECIAL_AUTHORITIES VARCHAR(72) Previous list of special authorities. This is a single string containing the list
of special authorities separated by one blank.
Contains the null value if the value was not changed.

PREVIOUS_ALLOBJ VARCHAR(3) Previous *ALLOBJ special authority

YES Profile had *ALLOBJ special authority

Contains the null value if the value was not changed.

PREVIOUS_JOBCTL VARCHAR(3) Previous *JOBCTL special authority

YES Profile had *JOBCTL special authority

Contains the null value if the value was not changed.

PREVIOUS_SAVSYS VARCHAR(3) Previous *SAVSYS special authority

YES Profile had *SAVSYS special authority

Contains the null value if the value was not changed.

PREVIOUS_SECADM VARCHAR(3) Previous *SECADM special authority

YES Profile had *SECADM special authority

Contains the null value if the value was not changed.

PREVIOUS_SPLCTL VARCHAR(3) Previous *SPLCTL special authority

YES Profile had *SPLCTL special authority

Contains the null value if the value was not changed.

PREVIOUS_SERVICE VARCHAR(3) Previous *SERVICE special authority

YES Profile had *SERVICE special authority

Contains the null value if the value was not changed.

PREVIOUS_AUDIT VARCHAR(3) Previous *AUDIT special authority

YES Profile had *AUDIT special authority

Contains the null value if the value was not changed.

PREVIOUS_IOSYSCFG VARCHAR(3) Previous *IOSYSCFG special authority

YES Profile had *IOSYSCFG special authority

Contains the null value if the value was not changed.

GROUP_PROFILE_NAME VARCHAR(10) The user's group profile. Can contain the special value *NONE to indicate
the user is not a member of any group profiles.
Contains the null value if the value was not changed.

Database performance and query optimization 689


Table 159. AUDIT_JOURNAL_CP table function (continued)

Column Name Data Type Description

GROUP_OWNER VARCHAR(7) Owner of objects created as a member of a group profile.

*GRPPRF The user's group profile becomes the owner

*USRPRF The user's user profile becomes the owner

Contains the null value if the value was not changed.

GROUP_AUTHORITY VARCHAR(8) The authority the user's group profile has to objects the user creates.

*ALL ALL authority

*CHANGE CHANGE authority

*EXCLUDE The group is denied access

*NONE No authority is granted to the group profile

*USE USE authority

Contains the null value if the value was not changed.

GROUP_AUTHORITY_TYPE VARCHAR(8) The value of the group authority type parameter.

*PGP The group becomes the object's primary group and is given
the authority specified in GROUP_AUTHORITY.

*PRIVATE The authority defined in the GROUP_AUTHORITY is assigned


as private authority to the group profile.

Contains the null value if the value was not changed.

SUPPLEMENTAL_GROUP_LIST VARCHAR(150) The names of up to 15 supplemental group profiles for the user. Can
contain the special value *NONE to indicate the user has no supplemental
groups. Each entry except for the last one is padded with blanks to fill 10
characters.
Contains the null value if the value was not changed.

INITIAL_PROGRAM_LIBRARY VARCHAR(10) The library where the initial program is found. Can contain the special value
*LIBL.
Contains the null value if INITIAL_PROGRAM is *NONE or if the value was
not changed.

INITIAL_PROGRAM VARCHAR(10) The user's initial program. Can contain the special value *NONE to indicate
the user has no initial program.
Contains the null value if the value was not changed.

INITIAL_MENU_LIBRARY VARCHAR(10) The library where the initial menu is found. Can contain the special value
*LIBL.
Contains the null value if INITIAL_MENU is *SIGNOFF or if the value was
not changed.

INITIAL_MENU VARCHAR(10) The user's initial menu. Can contain the special value *SIGNOFF to indicate
the user is limited to running the initial program specified for this profile.
Contains the null value if the value was not changed.

CURRENT_LIBRARY_NAME VARCHAR(10) The user's current library. Can contain the special value *CRTDFT to indicate
the user has no current library.
Contains the null value if the value was not changed.

HOME_DIRECTORY VARGRAPHIC(5000) Path name of the home directory or the following special value:
CCSID 1200
*USRPRF The home directory assigned to the user will be /home/
USRPRF, where USRPRF is the name of the user profile.

Contains the null value if the value was not changed.

690 IBM i: Performance and Query Optimization


Table 159. AUDIT_JOURNAL_CP table function (continued)

Column Name Data Type Description

LOCALE_PATH_NAME VARGRAPHIC(5000) Path name of the locale or one of the following special values:
CCSID 1200
*C The C locale path name is assigned to this user.

*NONE No locale path name is assigned to this user.

*POSIX The POSIX locale path name is assigned to this user.

*SYSVAL The system value, QLOCALE, is used to determine the locale


path name to be assigned to this user.

Contains the null value if the value was not changed.

LIMIT_CAPABILITIES VARCHAR(8) The value of limited capabilities parameter.

*NO No limitations.

*PARTIAL The user can change the initial menu, but cannot change
the initial program, current library, or attention key handling
program. The user can run commands from command lines.

*YES The user cannot change the initial program, initial menu,
current library, and attention key handling programs. The user
cannot run commands from command lines.

Contains the null value if the value was not changed.

ASSISTANCE_LEVEL VARCHAR(9) The user interface that will be used.

*ADVANCED The expert system interface is used.

*BASIC The Operational Assistant user interface is used.

*INTERMED The system interface is used.

*SYSVAL The system value, QASTLVL, is used to determine the user


interface that will be used.

Contains the null value if the value was not changed.

USER_OPTIONS VARCHAR(70) The level of help information detail to be shown and the default function
of the Page Up and Page Down keys. This column can contain up to seven
values, each ten characters long.

*CLKWD Parameter keywords are shown instead of the possible


parameter values when a control language (CL) command
is prompted.

*EXPERT More detailed information is shown when the user is


performing display and edit options to define or change
the system.

*HLPFULL Help text is shown on a full display rather than in a


window.

*NONE Detailed information is not shown.

*NOSTSMSG Status messages are not displayed when sent to the user.

*PRTMSG A message is sent to this user's message queue when a


spooled file for this user is printed or held by the printer
writer.

*ROLLKEY The actions of the Page Up and Page Down keys are
reversed.

*STSMSG Status messages are displayed when sent to the user.

Contains the null value if the value was not changed.

SPECIAL_ENVIRONMENT VARCHAR(7) The special environment in which the user operates after signing on.

*NONE The user operates in the IBM i system environment after


signing on the system.

*S36 The user operates in the System/36 environment after signing


on the system.

*SYSVAL The system value, QSPCENV, is used to determine the system


environment in which the user operates after signing on the
system.

Contains the null value if the value was not changed.

Database performance and query optimization 691


Table 159. AUDIT_JOURNAL_CP table function (continued)

Column Name Data Type Description

DISPLAY_SIGNON_INFORMATION VARCHAR(7) Indicates if the sign-on information display is shown.

*NO The sign-on information display is not shown.

*SYSVAL The system value, QDSPSGNINF, is used to determine whether


the sign-on information display is shown.

*YES The sign-on information display is shown.

Contains the null value if the value was not changed.

LIMIT_DEVICE_SESSIONS VARCHAR(7) The number of device sessions allowed for a user is limited.

0 The user is not limited to a specific number of device sessions.


This value has the same meaning as *NO.

1 The user is limited to a single device session. This value has


the same meaning as *YES.

2-9 The user is limited to the specified number of device sessions.

*NO The user is not limited to a specific number of device sessions.

*SYSVAL The system value, QLMTDEVSSN, is used to determine


whether the user is limited to a specific number of device
sessions.

*YES The user is limited to a single device session.

Contains the null value if the value was not changed.

KEYBOARD_BUFFERING VARCHAR(10) The keyboard buffering value to be used when a job is initialized for this
user profile.

*NO The type-ahead feature and attention key buffering


option are not active.

*SYSVAL The system value, QKBDBUF, is used to determine the


keyboard buffering value.

*TYPEAHEAD The type-ahead feature is active, but the attention key


buffering option is not.

*YES The type-ahead feature and attention key buffering


option are active.

Contains the null value if the value was not changed.

MAXIMUM_ALLOWED_STORAGE BIGINT The amount of auxiliary storage (in kilobytes) assigned to store permanent
objects owned by this user profile in the system auxiliary storage pool (ASP)
and on all the basic ASPs combined. In addition, this value also controls the
maximum amount of auxiliary storage that can be used to store permanent
objects owned by this user profile on each Independent ASP (IASP). A value
of -1 indicates *NOMAX.
Contains the null value if the value was not changed.

PRIORITY_LIMIT INTEGER The value of the priority limit parameter. Values are 0 to 9.
Contains the null value if the value was not changed.

JOB_DESCRIPTION_LIBRARY VARCHAR(10) The library where the job description is found. Can contain the special value
*LIBL.
Contains the null value if the value was not changed.

JOB_DESCRIPTION VARCHAR(10) The job description used for jobs that start through subsystem work
station entries whose job description parameter values indicate the user
JOBD(*USRPRF).
Contains the null value if the value was not changed.

ALTERNATE_SUBSYSTEM_NAME VARCHAR(10) The alternative subsystem that will be used for this user, instead of the
default subsystem, whenever a connection is initiated to the server job
specified in ALTERNATE_SERVER_JOB_NAME.
Contains the null value when COMMAND_TYPE is not SQL or if the value was
not changed.

692 IBM i: Performance and Query Optimization


Table 159. AUDIT_JOURNAL_CP table function (continued)

Column Name Data Type Description

ALTERNATE_SERVER_JOB_NAME VARCHAR(10) When a connection to this server is initiated for this user it will be routed to
the subsystem specified in the ALTERNATIVE_SUBSYSTEM_NAME column.
Can contain the special value *ALL.
To understand the Server Job Name mapping to server names and the
default subsystem use, see Server table.
Contains the null value when COMMAND_TYPE is not SQL or if the value was
not changed.

ACCOUNTING_CODE VARCHAR(15) The accounting code that is associated with this user profile or the following
special value:

*BLANK An accounting code of 15 blanks is assigned to this user profile.

Contains the null value if the value was not changed.

MESSAGE_QUEUE_LIBRARY VARCHAR(10) The library where the message queue is found. Can contain the special
value *LIBL.
Contains the null value if the value was not changed.

MESSAGE_QUEUE VARCHAR(10) The message queue to which messages are sent or the following special
value:

*USRPRF A message queue with the same name as the user profile is
used as the message queue for this user. The message queue
is located in the QUSRSYS library.

Contains the null value if the value was not changed.

MESSAGE_QUEUE_DELIVERY_METHOD VARCHAR(7) How messages sent to the message queue for this user are to be delivered.

*BREAK The job to which the message queue is assigned is interrupted


when a message arrives at the message queue.

*DFT The default reply to the inquiry message is sent.

*HOLD The messages are held in the message queue until they are
requested by the user or program.

*NOTIFY The job to which the message queue is assigned is notified


when a message arrives at the message queue.

Contains the null value if the value was not changed.

MESSAGE_QUEUE_SEVERITY INTEGER The lowest severity code that a message can have and still be delivered to a
user in break or notify mode. This is a value from 0 to 99.
Contains the null value if the value was not changed.

PRINT_DEVICE VARCHAR(10) The default printer device for this user or one of the following special
values:

*SYSVAL The system value, QPRTDEV, is used to determine the printer


device.

*WRKSTN The printer assigned to the user's work station is used.

Contains the null value if the value was not changed.

OUTPUT_QUEUE_LIBRARY VARCHAR(10) The library where the output queue is found. Can contain the special value
*LIBL.
Contains the null value if the value was not changed.

OUTPUT_QUEUE VARCHAR(10) The output queue to be used by this user profile or one of the following
special values:

*DEV The output queue associated with the printer specified for
the Printer Device is used.

*WRKSTN The output queue assigned to the user's work station is used.

Contains the null value if the value was not changed.

ATTENTION_KEY_HANDLING_ VARCHAR(10) The library where the ATTN program is found. Can contain the special value
PROGRAM_LIBRARY *LIBL.
Contains the null value if the value was not changed.

Database performance and query optimization 693


Table 159. AUDIT_JOURNAL_CP table function (continued)

Column Name Data Type Description

ATTENTION_KEY_HANDLING_PROGRAM VARCHAR(10) The program to be used as the Attention (ATTN) key handling program for
this user or one of the following special values:

*ASSIST The Operational Assistant ATTN key handling program,


QEZMAIN, is used.

*NONE No ATTN key handling program is used by this user.

*SYSVAL The system value, QATNPGM, is used to determine the ATTN


key handling program.

Contains the null value if the value was not changed.

SORT_SEQUENCE_TABLE_LIBRARY VARCHAR(10) The the library where the sort sequence table is found. Can contain the
special value *LIBL.
Contains the null value if the value was not changed.

SORT_SEQUENCE_TABLE VARCHAR(10) The sort sequence table to be used for string comparisons for this user
profile or one of the following special values:

*HEX A sort sequence table is not used. The hexadecimal


values of the characters are used to determine the sort
sequence.

*LANGIDSHR A shared-weight sort table is used.

*LANGIDUNQ A unique-weight sort table is used.

*SYSVAL The system value, QSRTSEQ, is used to determine the


sort sequence table.

Contains the null value if the value was not changed.

LANGUAGE_ID VARCHAR(7) The language identifier to be used for this user profile or the following
special value:

*SYSVAL The system value, QLANGID, is used to determine the


language identifier.

Contains the null value if the value was not changed.

COUNTRY_OR_REGION_ID VARCHAR(7) The country or region identifier to be used for this user profile or the
following special value:

*SYSVAL The system value, QCNTRYID, is used to determine the country


or region ID.

Contains the null value if the value was not changed.

CCSID VARCHAR(7) The coded character set identifier (CCSID) to be used for this user profile.

*SYSVAL The system value, QCCSID, is used to determine the CCSID.

Contains the null value if the value was not changed.

CHARACTER_IDENTIFIER_CONTROL VARCHAR(9) The character identifier control (CHRIDCTL) for the job.

*DEVD Performs the same function as it does on the CHRID


parameter for display files, printer files, and panel groups.

*JOBCCSID Performs the same function as it does on the CHRID


parameter for display files, printer files, and panel groups.

*SYSVAL The system value, QCHRIDCTL, is used to determine the


CHRIDCTL for the job.

Contains the null value if the value was not changed.

694 IBM i: Performance and Query Optimization


Table 159. AUDIT_JOURNAL_CP table function (continued)

Column Name Data Type Description

LOCALE_JOB_ATTRIBUTES VARCHAR(60) The job attributes that are to be taken from the locale when the job is
initiated. This column can contain up to six values, each ten characters long.

*CCSID The coded character set identifier from the locale is used.

*DATFMT The date format from the locale is used.

*DATSEP The date separator from the locale is used.

*DECFMT The decimal format from the locale is used.

*NONE No job attributes are taken from the locale.

*SRTSEQ The sort sequence from the locale is used.

*SYSVAL The system value, QSETJOBATR, is used to determine which


job attributes are taken from the locale.

*TIMSEP The time separator from the locale is used.

Contains the null value if the value was not changed.

DOCUMENT_PASSWORD_CHANGED VARCHAR(3) Indicates if the document password has been changed.

YES Document password changed.

Contains the null value if the value was not changed.

DOCUMENT_PASSWORD_NONE VARCHAR(3) Indicates if the document password is *NONE.

YES Document password is *NONE.

Contains the null value if the value was not changed.

EIM_ID VARCHAR(128) Enterprise Identity Mapping (EIM) identifier name or the following special
value:

*USRPRF The EIM identifier is the same name as the user profile.

Contains the null value if no EIM values were changed.

EIM_ASSOCIATION_TYPE VARCHAR(7) EIM association type.

*ADMIN Administrative association.

*ALL All association types.

*SOURCE Source association.

*TARGET Target association.

*TGTSRC Target and source associations.

Contains the null value if no EIM values were changed.

EIM_ASSOCIATION_ACTION VARCHAR(8) EIM association action.

*ADD Add an association.

*REMOVE Remove an association.

*REPLACE Associations of the specified type will be removed from all


EIM identifiers that have an association for this user profile
and local EIM registry. A new association will be added to the
specified EIM identifier.

Contains the null value if no EIM values were changed.

CREATE_EIM_ID VARCHAR(11) Indicates whether the EIM identifier should be created if it does not exist.

*CRTEIMID EIM identifier gets created if it does not exist.

*NOCRTEIMID EIM identifier does not get created.

Contains the null value if no EIM values were changed.

USER_ID_NUMBER VARCHAR(10) The UID for the user. Can contain the special value *GEN to indicate the uid
number is generated for the user.
Contains the null value if the value was not changed.

Database performance and query optimization 695


Table 159. AUDIT_JOURNAL_CP table function (continued)

Column Name Data Type Description

GROUP_ID_NUMBER VARCHAR(10) The GID for the user. Can contain the special values *GEN to indicate the gid
number is generated for the user or *NONE to indicate the user profile does
not have a group profile.
Contains the null value if the value was not changed.

Example
• List any user profiles that were created in the last 6 months.

SELECT USER_PROFILE FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_CP(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 6 MONTHS
)
)
WHERE COMMAND_TYPE = 'CRT';

AUDIT_JOURNAL_DO table function


The AUDIT_JOURNAL_DO table function returns rows from the audit journal that contain information from
the DO (Delete Operation) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 160. AUDIT_JOURNAL_DO table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the DO audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Object was deleted (not under commitment control)

C A pending object delete was committed

D A pending object create was rolled back

P The object delete is pending (the delete was performed under


commitment control)

R A pending object delete was rolled back

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

OBJECT_LIBRARY VARCHAR(10) The name of the library containing the object.


Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) The name of the object.


Contains the null value if there is no object name.

OBJECT_TYPE VARCHAR(7) The type of the object.


Contains the null value if there is no object type.

OBJECT_ATTRIBUTE VARCHAR(10) The attribute for the object type.


Contains the null value if there is no object attribute.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object resides. A
value of *SYSBAS indicates the system ASP and all basic user ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.

PATH_NAME VARGRAPHIC(5000) The path name of the object.


CCSID 1200
Contains the null value if the object name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

696 IBM i: Performance and Query Optimization


Table 160. AUDIT_JOURNAL_DO table function (continued)

Column Name Data Type Description

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path name


for the object, instead it contains a relative path name. The
RELATIVE_DIRECTORY_FILE_ID can be used to form an absolute
path name with this relative path name.

YES The PATH_NAME column contains complete absolute path name for
the object.

Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the directory
that contains the object identified in the PATH_NAME column.
Contains the null value when PATH_NAME_INDICATOR is YES, or if the
file ID is not available or the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) The name of the object.


CCSID 1200
Contains the null value if the object name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the object is not in the
"root" (/), QOpenSys, or user-defined file systems.

OFFICE_USER VARCHAR(10) The name of the office user.


Contains the null value if there is no office user.

OFFICE_ON_BEHALF_OF_USER VARCHAR(10) User working on behalf of another user.


Contains the null value if the user name is not available.

DLO_NAME VARCHAR(12) The name of the document library object.


Contains the null value if there is no document library object.

FOLDER_PATH VARCHAR(63) The path of the folder.


Contains the null value if there is no folder path.

Example
• List any *FILE objects that were deleted this week. Return the user profile in effect when the delete
occurred.

SELECT OBJECT_LIBRARY, OBJECT_NAME, USER_NAME FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_DO(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS
)
) WHERE OBJECT_TYPE = '*FILE';

AUDIT_JOURNAL_DS table function


The AUDIT_JOURNAL_DS table function returns rows from the audit journal that contain information from
the DS (Service Tools User ID and Attribute Changes) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.

Database performance and query optimization 697


Table 161. AUDIT_JOURNAL_DS table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the DS audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Reset of a service tools user ID password using the Change IBM


Service Tools Pwd (CHGDSTPWD) command.

C Change to a service tools user ID using the Change Service Tools User
ID (QSYCHGDS) API.

D Delete of a service tools user ID using the Delete Service Tools User ID
(DLTSSTUSR) command.

H Change to a service tools user ID using the Change Service Tools User
ID (CHGSSTUSR) command.

P Change to a service tools user ID password using the Change Service


Tools User ID (QSYCHGDS) API.

R Create of a service tools user ID using the Create Service Tools User ID
(CRTSSTUSR) command.

S Change to the service tools security attributes using the Change SST
Security Attributes (CHGSSTSECA) command.

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

SST_USERID VARCHAR(10) The name of the service tools user ID that requested the action.
Contains the null value when ENTRY_TYPE is A.

SST_USERID_MODIFIED VARCHAR(10) The service tools user ID being created, changed, renamed, or deleted.
When ENTRY_TYPE is C or P, it can contain one of the following special
values.

*BASIC

*FULL

*SECURITY

*SERVICE

Contains the null value when ENTRY_TYPE is not C, D, H, P, or R.

SST_USERID_NEW VARCHAR(10) The new service tools user ID when a user ID is renamed.
Contains the null value when ENTRY_TYPE is not C.

SET_PASSWORD_EXPIRED VARCHAR(3) Set password to expired.

NO Password is not set to expired

YES Password is set to expired

Contains the null value when ENTRY_TYPE is not H or R.

USERID_STATUS VARCHAR(9) Status of the user ID.

*DISABLED

*ENABLED

Contains the null value when ENTRY_TYPE is not H or R, or if ENTRY_TYPE is


H but no status is available.

PREV_USERID_STATUS VARCHAR(9) Previous status of the user ID.

*DISABLED

*ENABLED

Contains the null value when ENTRY_TYPE is not H or R, or if ENTRY_TYPE is


H but no status is available.

LINKED_PROFILE VARCHAR(10) The user profile that is linked to the service tools user ID.
Contains the null value when ENTRY_TYPE is not H or R, or there is no linked
user profile.

698 IBM i: Performance and Query Optimization


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

PREV_LINKED_PROFILE VARCHAR(10) The user profile that was previously linked to the service tools user ID.
Contains the null value when ENTRY_TYPE is not H, or no user profile was
previously linked.

ALLOW_SECURITY_SYSVAL_CHANGE VARCHAR(3) Allow changes to security related system values.

NO Do not allow changes

YES Allow changes

Contains the null value when this security attribute did not change or when
ENTRY_TYPE is not S.

PREV_ALLOW_SECURITY_SYSVAL_CHANGE VARCHAR(3) Previous value of allow changes to security related system values.

NO Do not allow changes

YES Allow changes

Contains the null value when this security attribute did not change or when
ENTRY_TYPE is not S.

PASSWORD_LEVEL INTEGER System Service Tools (SST) password level. The service tools password
rules are similar to the values that are specified in the Password Rules
(QPWDRULES) system value.
Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_LIMIT_USERID VARCHAR(3) Limit SST user profile name.

NO The password can contain the upper case profile name.

YES The password must not contain the upper case profile name.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_CHANGE_BLOCK INTEGER After a password change, the number of hours during which the password is
blocked from being changed again.

0 There is no restriction on how frequently a user can change a


password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_MINIMUM_LENGTH INTEGER Minimum password length.


Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_MAXIMUM_LENGTH INTEGER Maximum password length.


Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_REQUIRE_GROUPS VARCHAR(3) The password must contain characters from at least three of the four
types of characters: Uppercase letters, lowercase letters, digits, and special
characters.

NO The password is not required to contain characters from multiple


groups.

YES The password must contain characters from at least three of the
four groups.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_LIMIT_ADJACENT VARCHAR(3) Limit adjacent characters.

NO The password has no limit for adjacent (consecutive) characters.

YES The password may not contain two or more adjacent characters.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

Database performance and query optimization 699


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

PASSWORD_LIMIT_REPEAT VARCHAR(3) Limit repeating characters.

NO The password can contain multiple occurrences of the same


character.

YES The password may not contain two or more occurrences of the
same character.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_LIMIT_POSITIONS VARCHAR(3) Limit characters in the same position.

NO Characters can be used in the same position as in the previous


password.

YES The same character may not be used in the same position as in the
previous password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_REQUIRE_DIGIT INTEGER The minimum number of digit characters that must occur in the password.

0 No digits are required.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_MAXIMUM_DIGITS VARCHAR(6) The maximum number of digit characters that may occur in the password.

*NOMAX Any number of digits are allowed in the password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_LIMIT_DIGITS VARCHAR(3) Limit adjacent digits.

NO The password has no limit for adjacent (consecutive) digits.

YES The password must not contain two or more adjacent (consecutive)
digits.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_LIMIT_DIGIT_FIRST VARCHAR(3) Limit digit in first position.

NO The first character of the password can be a digit.

YES The first character of the password must not be a digit.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_LIMIT_DIGIT_LAST VARCHAR(3) Limit digit in last position.

NO The last character of the password can be a digit.

YES The last character of the password must not be a digit.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_REQUIRE_LETTER INTEGER The minimum number of letter characters that must occur in the password.

0 No letters are required.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_MAXIMUM_LETTERS VARCHAR(6) The maximum number of letter characters that may occur in the password.

*NOMAX Any number of letters are allowed in a password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

700 IBM i: Performance and Query Optimization


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

PASSWORD_LIMIT_LETTERS VARCHAR(3) Limit adjacent letters.

NO The password has no limit for adjacent (consecutive) letters.

YES The password must not contain two or more adjacent (consecutive)
letters.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_LIMIT_LETTER_FIRST VARCHAR(3) Limit letter in first position.

NO The first character of the password can be a letter.

YES The first character of the password must not be a letter.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_LIMIT_LETTER_LAST VARCHAR(3) Limit letter in last position.

NO The last character of the password can be a letter.

YES The last character of the password must not be a letter.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_REQUIRE_MIXED_CASE INTEGER The password must contain at least the specified number of uppercase and
lowercase letters.

0 Mixed case letters are not required in a password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_REQUIRE_SPECIAL INTEGER The minimum number of special characters that must occur in the
password.

0 No special characters are required.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_MAXIMUM_SPECIAL VARCHAR(6) The maximum number of special characters that may occur in the
password.

*NOMAX Any number of special characters are allowed in a password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_LIMIT_SPECIAL VARCHAR(3) Limit adjacent special characters.

NO The password has no limit for adjacent (consecutive) special


characters.

YES The password must not contain two or more adjacent (consecutive)
special characters.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_LIMIT_SPECIAL_FIRST VARCHAR(3) Limit special character in first position.

NO The first character of the password can be a special character.

YES The first character of the password must not be a special character.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PASSWORD_LIMIT_SPECIAL_LAST VARCHAR(3) Limit special character in last position.

NO The last character of the password can be a special character.

YES The last character of the password must not be a special character.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

Database performance and query optimization 701


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

PREV_PASSWORD_LEVEL INTEGER Previous System Service Tools password level.


Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_USERID VARCHAR(3) The previous value for limit SST user profile name.

NO The password can contain the upper case profile name.

YES The password must not contain the upper case profile name.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_CHANGE_BLOCK INTEGER The previous value for the number of hours during which the password is
blocked from being changed a second time.

0 There is no restriction on how frequently a user can change a


password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_MINIMUM_LENGTH INTEGER The previous value for minimum password length.


Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_MAXIMUM_LENGTH INTEGER The previous value for maximum password length.


Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_REQUIRE_GROUPS VARCHAR(3) The previous value for password must contain characters from at least three
of the four types of characters: Uppercase letters, lowercase letters, digits,
and special characters.

NO The password is not required to contain characters from multiple


groups.

YES The password must contain characters from at least three of the
four groups.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_ADJACENT VARCHAR(3) The previous value for limit adjacent characters.

NO The password has no limit for adjacent (consecutive) characters.

YES The password may not contain two or more adjacent (consecutive)
characters.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_REPEAT VARCHAR(3) The previous value for limit repeating characters.

NO The password can contain multiple occurrences of the same


character.

YES The password may not contain two or more occurrences of the
same character.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_POSITIONS VARCHAR(3) The previous value for limit characters in the same position.

NO Characters can be used in the same position as in the previous


password.

YES The same character may not be used in the same position as in the
previous password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

702 IBM i: Performance and Query Optimization


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

PREV_PASSWORD_REQUIRE_DIGIT INTEGER The previous value for the minimum number of digit characters that must
occur in the password.

0 No digits are required.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_MAXIMUM_DIGITS VARCHAR(6) The previous value for the maximum number of digit characters that may
occur in the password.

*NOMAX Any number of digits are allowed in the password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_DIGITS VARCHAR(3) The previous value for limit adjacent digits.

NO The password has no limit for adjacent (consecutive) digits.

YES The password must not contain two or more adjacent (consecutive)
digits.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_DIGIT_FIRST VARCHAR(3) The previous value for limit digit in first position.

NO The first character of the password can be a digit.

YES The first character of the password must not be a digit.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_DIGIT_LAST VARCHAR(3) The previous value for limit digit in last position.

NO The last character of the password can be a digit.

YES The last character of the password must not be a digit.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_REQUIRE_LETTER INTEGER The previous value for the minimum number of letter characters that must
occur in the password.

0 No letters are required.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_MAXIMUM_LETTERS VARCHAR(6) The previous value for the maximum number of letter characters that may
occur in the password.

*NOMAX Any number of letters are allowed in a password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_LETTERS VARCHAR(3) The previous value for limit adjacent letters.

NO The password has no limit for adjacent (consecutive) letters.

YES The password must not contain two or more adjacent (consecutive)
letters.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_LETTER_FIRST VARCHAR(3) The previous value for limit letter in first position.

NO The first character of the password can be a letter.

YES The first character of the password must not be a letter.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

Database performance and query optimization 703


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

PREV_PASSWORD_LIMIT_LETTER_LAST VARCHAR(3) The previous value for limit letter in last position.

NO The last character of the password can be a letter.

YES The last character of the password must not be a letter.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_REQUIRE_MIXED_CASE INTEGER The previous value for yhe password must contain at least the specified
number of uppercase and lowercase letters.

0 Mixed case letters are not required in a password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_REQUIRE_SPECIAL INTEGER The previous value for the minimum number of special characters that must
occur in the password.

0 No special characters are required.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_MAXIMUM_SPECIAL VARCHAR(6) The previous value for the maximum number of special characters that may
occur in the password.

*NOMAX Any number of special characters are allowed in a password.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_SPECIAL VARCHAR(3) The previous value for limit adjacent special characters.

NO The password has no limit for adjacent (consecutive) special


characters.

YES The password must not contain two or more adjacent (consecutive)
special characters.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_SPECIAL_FIRST VARCHAR(3) The previous value for limit special character in first position.

NO The first character of the password can be a special character.

YES The first character of the password must not be a special character.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

PREV_PASSWORD_LIMIT_SPECIAL_LAST VARCHAR(3) The previous value for limit special character in last position.

NO The last character of the password can be a special character.

YES The last character of the password must not be a special character.

Contains the null value when this value did not change or when
ENTRY_TYPE is not S.

DISK_OPERATIONS VARCHAR(3) Current privilege to perform disk operator service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

DISK_ADMIN VARCHAR(3) Current privilege to perform disk unit administrator service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

704 IBM i: Performance and Query Optimization


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

DISK_READ_ONLY VARCHAR(3) Current privilege to perform disk read only service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

SYSTEM_PARTITION_OPERATIONS VARCHAR(3) Current privilege to perform system partition operator service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

SYSTEM_PARTITION_ADMIN VARCHAR(3) Current privilege to perform system partition administrator service


functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

PARTITION_REMOTE_PANEL_KEY VARCHAR(3) Current privilege to change a panel key for the specified partition where it is
secured.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

OPERATOR_PANEL_FUNCTIONS VARCHAR(3) Current privilege to use the operator panel functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

IPL VARCHAR(3) Current privilege to perform an IPL.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

INSTALL VARCHAR(3) Current privilege to perform a system install.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

PDC VARCHAR(3) Current privilege to perform Performance Data Collector (PDC) service
functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

Database performance and query optimization 705


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

HSM VARCHAR(3) Current privilege to perform Hardware Service Manager (HSM) functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

DAD VARCHAR(3) Current privilege to work with Display/Alter/Dump.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

MSD VARCHAR(3) Current privilege to perform a main storage dump.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

PAL VARCHAR(3) Current privilege to view and work with the Product Activity Log (PAL).

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

LIC_LOG VARCHAR(3) Current privilege to view and work with the Licensed Internal Code (LIC) log.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

LIC_PTFS VARCHAR(3) Current privilege to load Licensed Internal Code (LIC) PTFs.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

TRACE VARCHAR(3) Current privilege to read and perform the trace service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

DST VARCHAR(3) Current privilege to change the Dedicated Service Tools (DST) environment.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

REMOTE_SERVICE_SUPPORT VARCHAR(3) Current privilege to configure and connect to the system using the Remote
Service Support interface.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

706 IBM i: Performance and Query Optimization


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

SERVICE_TOOLS_SECURITY VARCHAR(3) Current privilege to work with and change Licensed Internal Code (LIC)
security values.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

SERVICE_TOOLS_SAVE_RESTORE VARCHAR(3) Current privilege to perform save and restore service security functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

DEBUG VARCHAR(3) Current privilege to use the service debug tools.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

SYSTEM_CAPACITY_OPERATIONS VARCHAR(3) Current privilege to perform system capacity operations service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

SYSTEM_CAPACITY_ADMIN VARCHAR(3) Current privilege to perform system capacity administration service


functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

SYSTEM_SECURITY VARCHAR(3) Current privilege to perform security service functions and to work with
security lock down values.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

SST VARCHAR(3) Current privilege to sign-on and work with SST.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

TAKE_OVER_CONSOLE VARCHAR(3) Current privilege for a LAN console user to take over the console from
another LAN console user.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H or R, or it is H and the


privilege is not changing.

Database performance and query optimization 707


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

PREV_DISK_OPERATIONS VARCHAR(3) Previous privilege to perform disk operator service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_DISK_ADMIN VARCHAR(3) Previous privilege to perform disk unit administrator service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_DISK_READ_ONLY VARCHAR(3) Previous privilege to perform disk read only service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_SYSTEM_PARTITION_OPERATIONS VARCHAR(3) Previous privilege to perform system partition operator service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_SYSTEM_PARTITION_ADMIN VARCHAR(3) Previous privilege to perform system partition administrator service


functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_PARTITION_REMOTE_PANEL_KEY VARCHAR(3) Previous privilege to change a panel key for the specified partition where it
is secured.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_OPERATOR_PANEL_FUNCTIONS VARCHAR(3) Previous privilege to use the operator panel functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_IPL VARCHAR(3) Previous privilege to perform an IPL.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

708 IBM i: Performance and Query Optimization


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

PREV_INSTALL VARCHAR(3) Previous privilege to perform a system install.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_PDC VARCHAR(3) Previous privilege to perform Performance Data Collector (PDC) service
functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_HSM VARCHAR(3) Previous privilege to perform Hardware Service Manager (HSM) functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_DAD VARCHAR(3) Previous privilege to work with Display/Alter/Dump.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_MSD VARCHAR(3) Previous privilege to perform a main storage dump.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_PAL VARCHAR(3) Previous privilege to view and work with the Product Activity Log (PAL).

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_LIC_LOG VARCHAR(3) Previous privilege to view and work with the Licensed Internal Code (LIC)
log.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_LIC_PTFS VARCHAR(3) Previous privilege to load Licensed Internal Code (LIC) PTFs.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

Database performance and query optimization 709


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

PREV_TRACE VARCHAR(3) Previous privilege to read and perform the trace service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_DST VARCHAR(3) Previous privilege to change the Dedicated Service Tools (DST)
environment.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_REMOTE_SERVICE_SUPPORT VARCHAR(3) Previous privilege to configure and connect to the system using the Remote
Service Support interface.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_SERVICE_TOOLS_SECURITY VARCHAR(3) Previous privilege to work with and change Licensed Internal Code (LIC)
security values.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_SERVICE_TOOLS_SAVE_RESTORE VARCHAR(3) Previous privilege to perform save and restore service security functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_DEBUG VARCHAR(3) Previous privilege to use the service debug tools.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_SYSTEM_CAPACITY_OPERATIONS VARCHAR(3) Previous privilege to perform system capacity operations service functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_SYSTEM_CAPACITY_ADMIN VARCHAR(3) Previous privilege to perform system capacity administration service


functions.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

710 IBM i: Performance and Query Optimization


Table 161. AUDIT_JOURNAL_DS table function (continued)

Column Name Data Type Description

PREV_SYSTEM_SECURITY VARCHAR(3) Previous privilege to perform security service functions and to work with
security lock down values.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_SST VARCHAR(3) Previous privilege to sign-on and work with SST.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

PREV_TAKE_OVER_CONSOLE VARCHAR(3) Previous privilege for a LAN console user to take over the console from
another LAN console user.

NO Service tools user ID does not have the privilege

YES Service tools user ID has the privilege

Contains the null value when ENTRY_TYPE is not H, or it is H and the


privilege is not changing.

Example
• List SST users that were created or deleted in the last month

SELECT *
FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_DS (STARTING_TIMESTAMP => CURRENT TIMESTAMP - 1 MONTH)
)
WHERE ENTRY_TYPE IN ('D', 'R');

AUDIT_JOURNAL_EV table function


The AUDIT_JOURNAL_EV table function returns rows from the audit journal that contain information from
the EV (Environment Variable) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 162. AUDIT_JOURNAL_EV table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the EV audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Add

C Change

D Delete

I Initialize environment variable space

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

ENVIRONMENT_VARIABLE_NAME VARGRAPHIC(1000) The name of the environment variable.


CCSID 1200
Contains the null value when ENTRY_TYPE is I.

Database performance and query optimization 711


Table 162. AUDIT_JOURNAL_EV table function (continued)

Column Name Data Type Description

NAME_TRUNCATED VARCHAR(3) Indicates whether ENVIRONMENT_VARIABLE_NAME is truncated.

NO Environment variable name is not truncated.

YES Environment variable name is truncated.

Contains the null value when ENVIRONMENT_VARIABLE_NAME is null.

ENVIRONMENT_VARIABLE_VALUE VARGRAPHIC(1000) The value of the environment variable.


CCSID 1200
Contains the null value when no environment variable value is available.

VALUE_TRUNCATED VARCHAR(3) Indicates whether ENVIRONMENT_VARIABLE_VALUE is truncated.

NO Environment variable value is not truncated.

YES Environment variable value is truncated.

Contains the null value when ENVIRONMENT_VARIABLE_VALUE is null.

Example
• List any environment variables that have been changed in the last month.

SELECT *
FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_EV (STARTING_TIMESTAMP => CURRENT DATE - 1 MONTH))
)
WHERE ENTRY_TYPE = 'C';

AUDIT_JOURNAL_GR table function


The AUDIT_JOURNAL_GR table function returns rows from the audit journal that contain information from
the GR (Generic Record) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 163. AUDIT_JOURNAL_GR table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the GR audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Exit program added

D Exit program removed

F Function registration operations

O ObjectConnect operations

R Exit program replaced

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

ACTION CHAR(2) The action performed.

ZC Change

ZR Read

When ENTRY_TYPE is O:

SV Save

RS Restore

712 IBM i: Performance and Query Optimization


Table 163. AUDIT_JOURNAL_GR table function (continued)

Column Name Data Type Description

ACTION_DETAIL VARCHAR(200) Descriptive text that describes the action.

EXIT_POINT_NAME VARCHAR(20) When ENTRY_TYPE is A, D, or R, the exit point name.


Contains the null value when ENTRY_TYPE is F, or O.

EXIT_POINT_FORMAT CHAR(8) When ENTRY_TYPE is A, D, or R, the exit point format name associated with
the exit point
Contains the null value when ENTRY_TYPE is F, or O.

EXIT_PROGRAM_NUMBER INTEGER When ENTRY_TYPE is A, D, or R, the exit program number associated with
the exit program.
Contains the null value when ENTRY_TYPE is F, or O.

EXIT_PROGRAM_LIBRARY VARCHAR(10) When ENTRY_TYPE is A, D, or R, the library in which EXIT_PROGRAM


resides.
Contains the null value when ENTRY_TYPE is F, or O.

EXIT_PROGRAM VARCHAR(10) When ENTRY_TYPE is A, D, or R, the name of the exit program..


Contains the null value when ENTRY_TYPE is F, or O.

USER_PROFILE_NAME VARCHAR(10) User profile name


When ENTRY_TYPE is F, contains the name of the user the function
registration operation was performed against. When a REGISTER or
REREGISTER operation is being performed that includes the default usage,
contains *DEFAULT.
When ENTRY_TYPE is O, contains the name of the user performing the
ObjectConnect operation.
Contains the null value when ENTRY_TYPE is A, D, or R, or if a user profile
name does not apply to the entry.

FUNCTION _REGISTRATION_ VARCHAR(13) When ENTRY_TYPE is F, contains the description of the function registration
OPERATION operation that was performed. The possible values are:

CHANGE USAGE Function usage information has been changed, such as


which user profiles are allowed to use a function.

CHECK USAGE Function usage information was checked for a user and
determined the user is allowed to use the specified
function.

DEREGISTER Function and all associated usage information has


been removed from the registration facility.

REGISTER Function has been registered with the registration


facility.

REREGISTER Function has been updated and replaced within the


registration facility.

USAGE FAILURE Function usage information was checked for a user and
determined the user is not allowed to use the specified
function.

Contains the null value when ENTRY_TYPE is not F.

FUNCTION_NAME VARCHAR(30) When ENTRY_TYPE is F, contains the name of the function that was
operated on.
Contains the null value when ENTRY_TYPE is not F.

USAGE_SETTING VARCHAR(7) When ENTRY_TYPE is F, contains the usage value for the user specified in
USER_PROFILE_NAME. If USER_PROFILE_NAME is *DEFAULT, this is the
default usage.

ALLOWED The user is allowed to use the function.

DENIED The user is not allowed to use the function.

REMOVED The user's previous setting is removed.

UNKNOWN The user did not previously have a usage value.

Contains the null value when ENTRY_TYPE is not F or if no value is available.

Database performance and query optimization 713


Table 163. AUDIT_JOURNAL_GR table function (continued)

Column Name Data Type Description

PREVIOUS_USAGE VARCHAR(7) When ENTRY_TYPE is F, contains the previous usage value for a user. If
USER_PROFILE_NAME is *DEFAULT, this is the previous default usage.

ALLOWED The user is allowed to use the function.

DENIED The user is not allowed to use the function.

REMOVED The user's previous setting is removed.

UNKNOWN The user did not previously have a usage value.

Contains the null value when ENTRY_TYPE is not F or if no value is available.

FUNCTION_ALLOBJ VARCHAR(8) When ENTRY_TYPE is F and FUNCTION _REGISTRATION_OPERATION is


REGISTER or REREGISTER, contains the setting that indicates whether all
object (*ALLOBJ) special authority may be used to give a user access to the
function.

NOT USED For a user with *ALLOBJ special authority to use the function,
the usage information specified for the function must indicate
that the user is allowed to use the function

USED A user with *ALLOBJ special authority is always allowed to


use the function.

Contains the null value when ENTRY_TYPE is not F or if no value is available.

PREVIOUS_ALLOBJ VARCHAR(8) When ENTRY_TYPE is F and FUNCTION _REGISTRATION_OPERATION is


REREGISTER, contains the previous setting that indicates whether all object
(*ALLOBJ) special authority may be used to give a user access to the
function.

NOT USED For a user with *ALLOBJ special authority to use the function,
the usage information specified for the function must indicate
that the user is allowed to use the function

USED A user with *ALLOBJ special authority is always allowed to


use the function.

Contains the null value when ENTRY_TYPE is not F or if no value is available.

OBJECTCONNECT_COMMAND VARCHAR(9) When ENTRY_TYPE is O, contains the ObjectConnect CL command.

SAVRST Save/Restore Integrated File System Object

SAVRSTCFG Save/Restore Configuration

SAVRSTCHG Save/Restore Changed Object

SAVRSTDLO Save/Restore Document Library Object

SAVRSTLIB Save/Restore Library

SAVRSTOBJ Save/Restore Object

Contains the null value when ENTRY_TYPE is not O.

SAVE_SYSTEM VARCHAR(15) When ENTRY_TYPE is O and ACTION is RS, contains the name of the system
on which the objects are saved.
When ENTRY_TYPE is O and ACTION is SV, contains the name of the system
on which the objects are restored.
If ObjectConnect uses *DB2MIRROR for the connection type, the NRG name
is returned.
Contains the null value when ENTRY_TYPE is not O.

SAVE_ASP VARCHAR(10) When ENTRY_TYPE is O and OBJECTCONNECT_COMMAND is SAVRST,


SAVRSTCHG, SAVRSTLIB, or SAVRSTOBJ, the ASP device name. Can contain
one of the following special values:
• *
• *ALLAVL
• *ANY
• *CURASPGRP
• *SYSBAS
• 1-32
Contains the null value when ENTRY_TYPE is not O or there is no ASP
device.

714 IBM i: Performance and Query Optimization


Table 163. AUDIT_JOURNAL_GR table function (continued)

Column Name Data Type Description

SAVE_LIBRARY VARCHAR(10) When ENTRY_TYPE is O and OBJECTCONNECT_COMMAND is SAVRST,


SAVRSTCHG, SAVRSTLIB, or SAVRSTOBJ, the library name is set when
processing objects from the QSYS file system. It is the name of the saved
library or the library from which the objects were saved.
Contains the null value when ENTRY_TYPE is not O or there is no saved
library.

RESTORE_ASP_DEVICE VARCHAR(10) When ENTRY_TYPE is O and OBJECTCONNECT_COMMAND is SAVRST,


SAVRSTCHG, SAVRSTLIB, or SAVRSTOBJ, the ASP device name. Can contain
the following special value:
• *SAVASPDEV
Contains the null value when ENTRY_TYPE is not O or
RESTORE_ASP_NUMBER is set.

RESTORE_ASP_NUMBER VARCHAR(10) When ENTRY_TYPE is O and OBJECTCONNECT_COMMAND is SAVRST,


SAVRSTCHG, SAVRSTLIB, or SAVRSTOBJ, the ASP number, 1-32. Can
contain the following special value:
• *SAVASP
Contains the null value when ENTRY_TYPE is not O or
RESTORE_ASP_DEVICE is set.

RESTORE_LIBRARY VARCHAR(10) When ENTRY_TYPE is O and OBJECTCONNECT_COMMAND is SAVRST,


SAVRSTCHG, SAVRSTLIB, or SAVRSTOBJ, the library name is set when
processing objects from the QSYS file system otherwise it is blank. It is
the name of the restored library or the library to which the objects were
restored.
Contains the null value when ENTRY_TYPE is not O or there is no restore
library name.

OBJECTCONNECT_UUID VARCHAR(16) When ENTRY_TYPE is O, contains the Universal Unique Identifier (UUID) of
the ObjectConnect operation.
Contains the null value when ENTRY_TYPE is not O.

RESTORE_USER VARCHAR(10) When ENTRY_TYPE is O and ACTION is SV, contains the name of the user
under which the restore will be performed. Can contain the following special
values:

*CURRENT

*KERBEROS

*NONE

Contains the null value when ENTRY_TYPE is not O with an ACTION of SV.

Example
• List any changes to function usage definitions from the last two weeks

SELECT *
FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_GR (STARTING_TIMESTAMP => CURRENT DATE - 14 DAYS))
)
WHERE ENTRY_TYPE = 'F' AND
FUNCTION_REGISTRATION_OPERATION = 'CHANGE USAGE';

AUDIT_JOURNAL_IM table function


The AUDIT_JOURNAL_IM table function returns rows from the audit journal that contain information from
the IM (Intrusion Monitor) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.

Database performance and query optimization 715


Table 164. AUDIT_JOURNAL_IM table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the IM audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

P Potential intrusion event detected

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

EVENT_TIMESTAMP TIMESTAMP The date and time that the event was detected.

EVENT_LOCAL_ADDRESS_FAMILY CHAR(4) The type of local address associated with the detected event.

IPV4 The address is in IPv4 format.

IPV6 The address is in IPv6 format.

Contains the null value when a value is not available.

EVENT_LOCAL_ADDRESS VARCHAR(45) Local IP address associated with the detected event.


Contains the null value when a value is not available.

EVENT_LOCAL_PORT INTEGER Local port number associated with the detected event.
Contains the null value when a value is not available.

EVENT_REMOTE_ADDRESS_FAMILY CHAR(4) The type of remote address associated with the detected event.

IPV4 The address is in IPv4 format.

IPV6 The address is in IPv6 format.

Contains the null value when a value is not available.

EVENT_REMOTE_ADDRESS VARCHAR(45) Remote IP address associated with the detected event.


Contains the null value when a value is not available.

EVENT_REMOTE_PORT INTEGER Remote port number associated with the detected event.
Contains the null value when a value is not available.

PROBE_TYPE VARCHAR(6) The type of probe used to detect the potential intrusion.

ATTACK Attack event

OPEN Intrusion Detection System (IDS) state change

SCANE Scan event

SCANG Scan global event

TR-SSL Traffic regulation event (System TLS)

TR-TCP Traffic regulation event (TCP)

TR-UDP Traffic regulation event (UDP)

XATTAC Possible extrusion attack

XSCAN Outbound scan

XTRTCP Outbound traffic regulation event (TCP)

XTRUDP Outbound traffic regulation event (UDP)

PROBE_TYPE_DETAIL VARCHAR(200) Descriptive text for the probe type.

EVENT_CORRELATOR VARCHAR(4) Identifier for this specific intrusion event. This identifier can be used to
correlate this audit record with other intrusion detection information.

716 IBM i: Performance and Query Optimization


Table 164. AUDIT_JOURNAL_IM table function (continued)

Column Name Data Type Description

EVENT_ATTACK_TYPE VARCHAR(8) The type of potential intrusion that was detected.

ACKSTORM TCP ACK Storm

ADRPOISN Address Poisoning

FLOOD Flood

FRAGGLE Fraggle

ICMPRED ICMP Redirect

IPFRAG IP Fragment

MALFPKT Malformed Packet

OUTRAW Outbound Raw

PERPECH Perpetual Echo

PNGDEATH Ping of Death

RESTOPT Restricted IP Options

RESTPROT Restricted IP Protocol

SMURF Smurf

Contains the null value when PROBE_TYPE is not ATTACK or XATTAC.

EVENT_ATTACK_TYPE_DETAIL VARCHAR(200) Descriptive text for the type of potential intrusion.


Contains the null value when PROBE_TYPE is not ATTACK or XATTAC.

PROTOCOL VARCHAR(6) Protocol. Recognized protocol values and their protocol numbers are:

ICMP 1

ICMPV6 58

IGMP 2

OSPF 89

TCP 6

UDP 17

If the protocol is not one of these well-known values, the integer


representation of the protocol is returned.
Contains the null value when a value is not available.

CONDITION_NUMBER INTEGER Condition number from IDS policy file.


Contains the null value when a value is not available.

THROTTLING_ACTIVE VARCHAR(3) Throttling status at the time the event was flagged.

NO Throttling is not active.

YES Throttling is active.

DISCARDED_PACKETS INTEGER Number of discarded packets when throttled.


Contains the null value when THROTTLING_ACTIVE is NO.

TARGET_TCPIP_STACK VARCHAR(10) The type of TCP/IP stack that was targeted.

PRODUCTION Production Stack

SERVICE Service Stack

SUSPECTED_PACKET VARBINARY(1000) The first 1000 bytes of the IP packet associated with the detected event.
Contains the null value when PROBE_TYPE is TR-SSL or when a value is not
available.

FAILING_HANDSHAKE_LOCATION VARCHAR(6) The processing location that detected the failed handshake.
Contains the null value when PROBE_TYPE is not TR-SSL or when a value is
not available.

Database performance and query optimization 717


Table 164. AUDIT_JOURNAL_IM table function (continued)

Column Name Data Type Description

FAILING_HANDSHAKE_ERROR VARCHAR(40) The error returned on the failing handshake.


Contains the null value when PROBE_TYPE is not TR-SSL or when a value is
not available.

DETECTION_POINT_ID VARCHAR(4) A unique identifier for the processing location that detected the intrusion
event. This value is intended for use by service personnel.

Example
• List all intrusion events for this week.

SELECT * FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_IM(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS
)
);

AUDIT_JOURNAL_JS table function


The AUDIT_JOURNAL_JS table function returns rows from the audit journal that contain information from
the JS (Job Change) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 165. AUDIT_JOURNAL_JS table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the JS audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A ENDJOBABN command

B Submit

C Change

E End

H Hold

I Disconnect

J The current job is attempting to interrupt another job

K The current job is about to be interrupted

L The interruption of the current job has completed

M Change profile or group profile

N ENDJOB command

P Attach prestart or batch immediate job

Q Change query attributes

R Release

S Start

T Change profile or group profile using a profile token

U CHGUSRTRC

V Virtual device changed by QWSACCDS API

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

718 IBM i: Performance and Query Optimization


Table 165. AUDIT_JOURNAL_JS table function (continued)

Column Name Data Type Description

JOB_TYPE VARCHAR(3) The job type. This value is based on the values of the JOB_TYPE_BASIC and
JOB_SUBTYPE columns.

ASJ Autostart

BCH Batch

BCI Batch Immediate

EVK Started by a procedure start request

INT Interactive

M36 Advanced 36 server job

MRT Multiple requester terminal

PDJ Print driver job

PJ Prestart job

RDR Spool reader

SBS Subsystem monitor

SYS System

WTR Spool writer

Contains the null value if no value is available.

JOB_TYPE_BASIC CHAR(1) The type of job.

A Autostart

B Batch

I Interactive

M Subsystem monitor

R Reader

S System

W Writer

X SCPF

Contains the null value if no value is available.

JOB_SUBTYPE CHAR(1) The subtype of the job.

D Batch immediate

E Procedure start request

J Prestart

P Print device driver

Q Query

T MRT

U Alternate spool user

Contains the null value if there is no subtype for the job.

TARGET_QUALIFIED_JOB_NAME VARCHAR(28) The qualified job name of the job that is being operated on.

TARGET_JOB_NAME VARCHAR(10) The name of the job that is being operated on.

TARGET_JOB_USER VARCHAR(10) The user profile that of the job that is being operated on.

TARGET_JOB_NUMBER VARCHAR(6) The job number of the job that is being operated on.

DEVICE_NAME VARCHAR(10) The name of the device.


Contains the null value if no value is available.

Database performance and query optimization 719


Table 165. AUDIT_JOURNAL_JS table function (continued)

Column Name Data Type Description

EFFECTIVE_USER_PROFILE VARCHAR(10) The name of the effective user profile for the thread.
When this audit record is generated because one job performs an operation
on another job this column contains data from the initial thread of the job
that is being operated on. In all other cases, the column contains data from
the thread that performed the operation.
Contains the null value if no value is available.

EFFECTIVE_GROUP_PROFILE VARCHAR(10) The name of the effective group profile for the thread.
When this audit record is generated because one job performs an operation
on another job, this column contains data from the initial thread of the job
that is being operated on. In all other cases, the column contains data from
the thread that performed the operation.
Contains the null value if no value is available.

SUPPLEMENTAL_GROUP_PROFILES VARCHAR(150) The names of the supplemental group profiles for the thread.
When this audit record is generated because one job performs an operation
on another job, this column contains data from the initial thread of the job
that is being operated on. In all other cases, the column contains data from
the thread that performed the operation.
Contains the null value if no value is available.

REAL_USER_PROFILE VARCHAR(10) The name of the real (initial) user profile for the thread.
Contains the null value if no value is available.

SAVED_USER_PROFILE VARCHAR(10) The name of the saved user profile for the thread.
Contains the null value if no value is available.

REAL_GROUP_PROFILE VARCHAR(10) The name of the real (initial) group profile for the thread.
Contains the null value if no value is available.

SAVED_GROUP_PROFILE VARCHAR(10) The name of the saved group profile for the thread.
Contains the null value if no value is available.

REAL_USER_CHANGED VARCHAR(3) The real user profile was changed.

NO The real user profile was not changed.

YES The real user profile was changed.

Contains the null value when ENTRY_TYPE is not M or T.

EFFECTIVE_USER_CHANGED VARCHAR(3) The effective user profile was changed.

NO The effective user profile was not changed.

YES The effective user profile was changed.

Contains the null value when ENTRY_TYPE is not M or T.

SAVED_USER_CHANGED VARCHAR(3) The saved user profile was changed.

NO The saved user profile was not changed.

YES The saved user profile was changed.

Contains the null value when ENTRY_TYPE is not M or T.

REAL_GROUP_CHANGED VARCHAR(3) The real group profile was changed.

NO The real group profile was not changed.

YES The real group profile was changed.

Contains the null value when ENTRY_TYPE is not M or T.

EFFECTIVE_GROUP_CHANGED VARCHAR(3) The effective group profile was changed.

NO The effective group profile was not changed.

YES The effective group profile was changed.

Contains the null value when ENTRY_TYPE is not M or T.

720 IBM i: Performance and Query Optimization


Table 165. AUDIT_JOURNAL_JS table function (continued)

Column Name Data Type Description

SAVED_GROUP_CHANGED VARCHAR(3) The saved group profile was changed.

NO The saved group profile was not changed.

YES The saved group profile was changed.

Contains the null value when ENTRY_TYPE is not M or T.

SUPPLEMENTAL_GROUPS_CHANGED VARCHAR(3) The supplemental group profiles were changed.

NO The supplemental group profiles were not changed.

YES The supplemental group profiles were changed.

Contains the null value when ENTRY_TYPE is not M or T.

JOB_DESCRIPTION_LIBRARY VARCHAR(10) The name of the library for the job description.
Contains the null value if no value is available.

JOB_DESCRIPTION VARCHAR(10) The name of the job description for the job.
Contains the null value if no value is available.

JOB_DESCRIPTION_ASP_NAME VARCHAR(10) ASP name for JOB_DESCRIPTION_LIBRARY.


Contains the null value if no value is available.

JOB_DESCRIPTION_ASP_NUMBER INTEGER ASP number for JOB_DESCRIPTION_LIBRARY.


Contains the null value if no value is available.

JOB_QUEUE_LIBRARY VARCHAR(10) The name of the library for the job queue.
Contains the null value if no value is available.

JOB_QUEUE_NAME VARCHAR(10) The name of the job queue for the job.
Contains the null value if no value is available.

JOB_QUEUE_ASP_NAME VARCHAR(10) ASP name for JOB_QUEUE_LIBRARY.


Contains the null value if no value is available.

JOB_QUEUE_ASP_NUMBER INTEGER ASP number of JOB_QUEUE_LIBRARY.


Contains the null value if no value is available.

OUTPUT_QUEUE_LIBRARY VARCHAR(10) The name of the library for the output queue.
Contains the null value if no value is available.

OUTPUT_QUEUE_NAME VARCHAR(10) The name of the output queue for the job.
Contains the null value if no value is available.

PRINTER_DEVICE VARCHAR(10) The name of the printer device for the job.
Contains the null value if no value is available.

TIME_ZONE_DESCRIPTION_NAME VARCHAR(10) The timezone description name.


Contains the null value if no value is available.

THREAD_ASP_NAME VARCHAR(10) The ASP group for the current thread.


Contains the null value if no value is available.

LIBRARY_LIST_COUNT INTEGER The number of libraries in LIBRARY_LIST.

LIBRARY_LIST VARCHAR(2680) The library list for the job. The list is an array of entries, each ten characters
long.
When this audit record is generated because one job performs an operation
on another job, this column contains data from the initial thread of the job
that is being operated on. In all other cases, the column contains data from
the thread that performed the operation.
Contains the null value when LIBRARY_LIST_COUNT is 0.

Database performance and query optimization 721


Table 165. AUDIT_JOURNAL_JS table function (continued)

Column Name Data Type Description

JOB_USER_IDENTITY_DESCRIPTION VARCHAR(5) Describes the meaning of JOB_USER_IDENTITY.

CLEAR The clear JUID API was called. JOB_USER_IDENTITY contains


the new value.

JOB JOB_USER_IDENTITY contains the value for the JOB.

SET The set JUID API was called. JOB_USER_IDENTITY contains the
new value.

JOB_USER_IDENTITY VARCHAR(10) The job user identity value.


Contains the null value if no value is available.

WORKLOAD_GROUP VARCHAR(10) The name of the workload group associated with the job.
Contains the null value when ENTRY_TYPE is not C, E, or S.

EXIT_QUALIFIED_JOB_NAME VARCHAR(28) • When ENTRY_TYPE is J, the qualified job name of the job that was
interrupted by the current job.
• When ENTRY_TYPE is K or L, the qualified job name of the job that
requested the interruption of the current job.
Contains the null value when ENTRY_TYPE is not J, K, or L.

EXIT_JOB_NAME VARCHAR(10) • When ENTRY_TYPE is J, the name of the job that was interrupted by the
current job.
• When ENTRY_TYPE is K or L, the name of the job that requested the
interruption of the current job.
Contains the null value when ENTRY_TYPE is not J, K, or L.

EXIT_JOB_USER VARCHAR(10) • When ENTRY_TYPE is J, the user of the job that was interrupted by the
current job.
• When ENTRY_TYPE is K or L, the user of the job that requested the
interruption of the current job.
Contains the null value when ENTRY_TYPE is not J, K, or L.

EXIT_JOB_NUMBER VARCHAR(6) • When ENTRY_TYPE is J, the job number of the job that was interrupted by
the current job.
• When ENTRY_TYPE is K or L, the number of the job that requested the
interruption of the current job.
Contains the null value when ENTRY_TYPE is not J, K, or L.

EXIT_PROGRAM_LIBRARY VARCHAR(10) The library name of the exit program used to interrupt the job.
Contains the null value when ENTRY_TYPE is not J, K, or L.

EXIT_PROGRAM VARCHAR(10) The exit program used to interrupt the job.


Contains the null value when ENTRY_TYPE is not J, K, or L.

Example
• List jobs that were ended today with the ENDJOB or ENDJOBABN CL commands.

SELECT *
FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_JS (STARTING_TIMESTAMP => CURRENT DATE)
)
WHERE ENTRY_TYPE IN ('A','N');

AUDIT_JOURNAL_LD table function


The AUDIT_JOURNAL_LD table function returns rows from the audit journal that contain information from
the LD (Link, Unlink, Search Directory) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.

722 IBM i: Performance and Query Optimization


Table 166. AUDIT_JOURNAL_LD table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the LD audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

K Search directory

L Link directory

U Unlink directory

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

PATH_NAME VARGRAPHIC(5000) The path name of the object.


CCSID 1200
Contains the null value if the path name is not available.

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path name


for the object, instead it contains a relative path name. The
RELATIVE_DIRECTORY_FILE_ID can be used to form an absolute
path name with this relative path name.

YES The PATH_NAME column contains complete absolute path name for
the object.

Contains the null value if the path name is not available.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the directory
that contains the object identified in the PATH_NAME column.
Contains the null value if the path name is not available, or the
PATH_NAME_INDICATOR is YES, or the file ID is not available.

IFS_OBJECT_NAME VARGRAPHIC(512) The name of the object.


CCSID 1200

OBJECT_FILE_ID BINARY(16) The file ID of the object.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object resides. A
value of *SYSBAS indicates the system ASP and all basic user ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the auxiliary storage pool to which storage for the object is
allocated.

Example
• List directories that have been searched in the last week.

SELECT PATH_NAME FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_LD(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS)
)
WHERE ENTRY_TYPE = 'K';

AUDIT_JOURNAL_M0 table function


The AUDIT_JOURNAL_M0 table function returns rows from the audit journal that contain information from
the M0 (Db2 Mirror Setup Tools) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.

Database performance and query optimization 723


Table 167. AUDIT_JOURNAL_M0 table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the M0 audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Db2 Mirror setup tools

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

ACTION VARCHAR(15) The action performed.

CHECKSYSBASE Verify the cloning of SYSBASE and the


configuration of the setup copy node has
completed successfully.

CONFIGFILE Manipulate the JSON configuration files.

FLASHCOPY Perform the flash copy process on the storage.

IASPCOPY Perform the entire automated DB IASP clone


process.

POSTIASP Perform the post-IASP copy steps.

POWEROFF Power® off the setup source or copy node using the
HMC poweroff operation.

PRECHECK Perform validation and checking to ensure the


whole cloning process will complete successfully.

PREIASP Perform the pre-IASP copy steps.

REMOTECOPY Perform the remote copy process on the storage.

START Begin the entire SYSBASE cloning process.

STARTWARMCLONE Start Db2 Mirror tracking and flush main memory


on the setup source node.

ACTION_TYPE VARCHAR(10) The type of action being performed.


When ACTION is START or IASPCOPY:

COLD

WARM

When ACTION is CONFIGFILE:

NEW

RESTORE

SAVE

UPDATE

When ACTION is POWEROFF:

CONTROL

HMC

IMMED

Contains the null value if there is no action type.

ACTION_DETAIL VARCHAR(200) Descriptive text that corresponds to the action.


Contains the null value if ACTION_TYPE is null.

724 IBM i: Performance and Query Optimization


Table 167. AUDIT_JOURNAL_M0 table function (continued)

Column Name Data Type Description

ACTION_STATUS VARCHAR(12) Status of the action. This column can return a value when ACTION has
a value of START, CHECKSYSBASE, POWEROFF, PRECHECK, FLASHCOPY,
REMOTECOPY, and IASPCOPY. For these ACTION values, two audit entries
will be sent: one when the action starts and another when the action ends.
When the audit entry is for the start of the action, this column contains
STARTED. When the audit entry is for the end of the action, this column
contains the status of the action.

COMPLETED The action was successful

STARTED The action has started

UNSUCCESSFUL The action was not successful

Contains the null value if there is no status.

IASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP). A value of *SYSBAS indicates
the system ASP and all basic user ASPs.
Contains the null value if ACTION is not IASPCOPY, PREIASP, or POSTIASP.

SETUP_SOURCE_NODE VARCHAR(8) The partition name of the Db2 Mirror setup source node.

SETUP_COPY_NODE VARCHAR(8) The partition name of the Db2 Mirror setup copy node.

SETUP_SOURCE_STORAGE VARCHAR(256) The IP address or host and domain name of the setup source storage
system.
Contains the null value if ACTION is not START, PRECHECK, FLASHCOPY,
REMOTECOPY, or IASPCOPY.

SETUP_COPY_STORAGE VARCHAR(256) The IP address or host and domain name of the setup copy storage system.
Contains the null value if ACTION is not START, PRECHECK, FLASHCOPY,
REMOTECOPY, or IASPCOPY.

Example
• List any Db2 Mirror set up actions that were unsuccessful from the last week.

SELECT ENTRY_TIMESTAMP, IASP_NAME, ACTION, ACTION_TYPE, ACTION_DETAIL


FROM TABLE(
SYSTOOLS.AUDIT_JOURNAL_M0(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS
)
)
WHERE ACTION_STATUS = 'UNSUCCESSFUL';

AUDIT_JOURNAL_M6 table function


The AUDIT_JOURNAL_M6 table function returns rows from the audit journal that contain information from
the M6 (Db2 Mirror Communication Services) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 168. AUDIT_JOURNAL_M6 table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the M6 audit journal entry.

ENTRY_TYPE CHAR(1) The type of Network Redundancy Group (NRG) entry.

A Add NRG

C Change NRG

R Remove NRG

Database performance and query optimization 725


Table 168. AUDIT_JOURNAL_M6 table function (continued)

Column Name Data Type Description

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

NRG_NAME VARCHAR(15) The name associated with the NRG.

NRG_TYPE VARCHAR(12) Type of NRG.

UNSPECIFIED Unspecified

DB2 MIRROR Db2 Mirror

USER DEFINED User defined

Contains the null value if ENTRY_TYPE is R.

TEXT_DESCRIPTION VARCHAR(50) Text description.


Contains the null value if there is no text description or if ENTRY_TYPE is R.

LOAD_BALANCE_LINK_COUNT INTEGER Load balance link count.


Contains the null value if ENTRY_TYPE is R.

LINK_COUNT INTEGER Number of links configured in the group. This indicates the number of sets
of link information columns, with a suffix of _n, that contain values. The
information for links greater than LINK_COUNT will contain the null value.
Contains the null value if ENTRY_TYPE is R. All the link information columns
will contain the null value.

ADDRESS_SPACE_TYPE_1 CHAR(4) The address family of the first link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_1 VARCHAR(45) The local IP address for the first link.

LINE_DESCRIPTION_1 VARCHAR(10) The local line description for the first link.

VIRTUAL_LAN_ID_1 INTEGER The local VLAN ID for the first link.

TARGET_ADDRESS_1 VARCHAR(45) The remote IP address for the first link.

LINK_TYPE_1 CHAR(2) The link type of the first link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_1 INTEGER The priority of the first link.

ADDRESS_SPACE_TYPE_2 CHAR(4) The address family of the second link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_2 VARCHAR(45) The local IP address for the second link.

LINE_DESCRIPTION_2 VARCHAR(10) The local line description for the second link.

VIRTUAL_LAN_ID_2 INTEGER The local VLAN ID for the second link.

TARGET_ADDRESS_2 VARCHAR(45) The remote IP address for the second link.

LINK_TYPE_2 CHAR(2) The link type of the second link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_2 INTEGER The priority of the second link.

ADDRESS_SPACE_TYPE_3 CHAR(4) The address family of the third link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_3 VARCHAR(45) The local IP address for the third link.

LINE_DESCRIPTION_3 VARCHAR(10) The local line description for the third link.

726 IBM i: Performance and Query Optimization


Table 168. AUDIT_JOURNAL_M6 table function (continued)

Column Name Data Type Description

VIRTUAL_LAN_ID_3 INTEGER The local VLAN ID for the third link.

TARGET_ADDRESS_3 VARCHAR(45) The remote IP address for the third link.

LINK_TYPE_3 CHAR(2) The link type of the third link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_3 INTEGER The priority of the third link.

ADDRESS_SPACE_TYPE_4 CHAR(4) The address family of the fourth link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_4 VARCHAR(45) The local IP address for the fourth link.

LINE_DESCRIPTION_4 VARCHAR(10) The local line description for the fourth link.

VIRTUAL_LAN_ID_4 INTEGER The local VLAN ID for the fourth link.

TARGET_ADDRESS_4 VARCHAR(45) The remote IP address for the fourth link.

LINK_TYPE_4 CHAR(2) The link type of the fourth link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_4 INTEGER The priority of the fourth link.

ADDRESS_SPACE_TYPE_5 CHAR(4) The address family of the fifth link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_5 VARCHAR(45) The local IP address for the fifth link.

LINE_DESCRIPTION_5 VARCHAR(10) The local line description for the fifth link.

VIRTUAL_LAN_ID_5 INTEGER The local VLAN ID for the fifth link.

TARGET_ADDRESS_5 VARCHAR(45) The remote IP address for the fifth link.

LINK_TYPE_5 CHAR(2) The link type of the fifth link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_5 INTEGER The priority of the fifth link.

ADDRESS_SPACE_TYPE_6 CHAR(4) The address family of the sixth link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_6 VARCHAR(45) The local IP address for the sixth link.

LINE_DESCRIPTION_6 VARCHAR(10) The local line description for the sixth link.

VIRTUAL_LAN_ID_6 INTEGER The local VLAN ID for the sixth link.

TARGET_ADDRESS_6 VARCHAR(45) The remote IP address for the sixth link.

LINK_TYPE_6 CHAR(2) The link type of the sixth link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_6 INTEGER The priority of the sixth link.

Database performance and query optimization 727


Table 168. AUDIT_JOURNAL_M6 table function (continued)

Column Name Data Type Description

ADDRESS_SPACE_TYPE_7 CHAR(4) The address family of the seventh link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_7 VARCHAR(45) The local IP address for the seventh link.

LINE_DESCRIPTION_7 VARCHAR(10) The local line description for the seventh link.

VIRTUAL_LAN_ID_7 INTEGER The local VLAN ID for the seventh link.

TARGET_ADDRESS_7 VARCHAR(45) The remote IP address for the seventh link.

LINK_TYPE_7 CHAR(2) The link type of the seventh link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_7 INTEGER The priority of the seventh link.

ADDRESS_SPACE_TYPE_8 CHAR(4) The address family of the eighth link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_8 VARCHAR(45) The local IP address for the eighth link.

LINE_DESCRIPTION_8 VARCHAR(10) The local line description for the eighth link.

VIRTUAL_LAN_ID_8 INTEGER The local VLAN ID for the eighth link.

TARGET_ADDRESS_8 VARCHAR(45) The remote IP address for the eighth link.

LINK_TYPE_8 CHAR(2) The link type of the eighth link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_8 INTEGER The priority of the eighth link.

ADDRESS_SPACE_TYPE_9 CHAR(4) The address family of the ninth link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_9 VARCHAR(45) The local IP address for the ninth link.

LINE_DESCRIPTION_9 VARCHAR(10) The local line description for the ninth link.

VIRTUAL_LAN_ID_9 INTEGER The local VLAN ID for the ninth link.

TARGET_ADDRESS_9 VARCHAR(45) The remote IP address for the ninth link.

LINK_TYPE_9 CHAR(2) The link type of the ninth link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_9 INTEGER The priority of the ninth link.

ADDRESS_SPACE_TYPE_10 CHAR(4) The address family of the tenth link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_10 VARCHAR(45) The local IP address for the tenth link.

LINE_DESCRIPTION_10 VARCHAR(10) The local line description for the tenth link.

VIRTUAL_LAN_ID_10 INTEGER The local VLAN ID for the tenth link.

TARGET_ADDRESS_10 VARCHAR(45) The remote IP address for the tenth link.

728 IBM i: Performance and Query Optimization


Table 168. AUDIT_JOURNAL_M6 table function (continued)

Column Name Data Type Description

LINK_TYPE_10 CHAR(2) The link type of the tenth link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_10 INTEGER The priority of the tenth link.

ADDRESS_SPACE_TYPE_11 CHAR(4) The address family of the eleventh link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_11 VARCHAR(45) The local IP address for the eleventh link.

LINE_DESCRIPTION_11 VARCHAR(10) The local line description for the eleventh link.

VIRTUAL_LAN_ID_11 INTEGER The local VLAN ID for the eleventh link.

TARGET_ADDRESS_11 VARCHAR(45) The remote IP address for the eleventh link.

LINK_TYPE_11 CHAR(2) The link type of the eleventh link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_11 INTEGER The priority of the eleventh link.

ADDRESS_SPACE_TYPE_12 CHAR(4) The address family of the twelfth link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_12 VARCHAR(45) The local IP address for the twelfth link.

LINE_DESCRIPTION_12 VARCHAR(10) The local line description for the twelfth link.

VIRTUAL_LAN_ID_12 INTEGER The local VLAN ID for the twelfth link.

TARGET_ADDRESS_12 VARCHAR(45) The remote IP address for the twelfth link.

LINK_TYPE_12 CHAR(2) The link type of the twelfth link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_12 INTEGER The priority of the twelfth link.

ADDRESS_SPACE_TYPE_13 CHAR(4) The address family of the thirteenth link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_13 VARCHAR(45) The local IP address for the thirteenth link.

LINE_DESCRIPTION_13 VARCHAR(10) The local line description for the thirteenth link.

VIRTUAL_LAN_ID_13 INTEGER The local VLAN ID for the thirteenth link.

TARGET_ADDRESS_13 VARCHAR(45) The remote IP address for the thirteenth link.

LINK_TYPE_13 CHAR(2) The link type of the thirteenth link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_13 INTEGER The priority of the thirteenth link.

ADDRESS_SPACE_TYPE_14 CHAR(4) The address family of the fourteenth link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

Database performance and query optimization 729


Table 168. AUDIT_JOURNAL_M6 table function (continued)

Column Name Data Type Description

SOURCE_ADDRESS_14 VARCHAR(45) The local IP address for the fourteenth link.

LINE_DESCRIPTION_14 VARCHAR(10) The local line description for the fourteenth link.

VIRTUAL_LAN_ID_14 INTEGER The local VLAN ID for the fourteenth link.

TARGET_ADDRESS_14 VARCHAR(45) The remote IP address for the fourteenth link.

LINK_TYPE_14 CHAR(2) The link type of the fourteenth link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_14 INTEGER The priority of the fourteenth link.

ADDRESS_SPACE_TYPE_15 CHAR(4) The address family of the fifteenth link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_15 VARCHAR(45) The local IP address for the fifteenth link.

LINE_DESCRIPTION_15 VARCHAR(10) The local line description for the fifteenth link.

VIRTUAL_LAN_ID_15 INTEGER The local VLAN ID for the fifteenth link.

TARGET_ADDRESS_15 VARCHAR(45) The remote IP address for the fifteenth link.

LINK_TYPE_15 CHAR(2) The link type of the fifteenth link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_15 INTEGER The priority of the fifteenth link.

ADDRESS_SPACE_TYPE_16 CHAR(4) The address family of the sixteenth link.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

SOURCE_ADDRESS_16 VARCHAR(45) The local IP address for the sixteenth link.

LINE_DESCRIPTION_16 VARCHAR(10) The local line description for the sixteenth link.

VIRTUAL_LAN_ID_16 INTEGER The local VLAN ID for the sixteenth link.

TARGET_ADDRESS_16 VARCHAR(45) The remote IP address for the sixteenth link.

LINK_TYPE_16 CHAR(2) The link type of the sixteenth link.

V1 RoCE v1

V2 RoCE v2

LINK_PRIORITY_16 INTEGER The priority of the sixteenth link.

Example
• List NRG configuration changes from the last month

SELECT * FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_M6(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 1 MONTH
)
)
WHERE ENTRY_TYPE = 'C';

730 IBM i: Performance and Query Optimization


AUDIT_JOURNAL_M7 table function
The AUDIT_JOURNAL_M7 table function returns rows from the audit journal that contain information from
the M7 (Db2 Mirror Replication Services) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 169. AUDIT_JOURNAL_M7 table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the M7 audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Add active replication criteria rule

D Duplicate replication criteria rules (a rename library was performed)

P Activate pending replication criteria rules

R Remove active replication criteria rule

S Resynchronization of eligible objects

U User deferred or deleted entries in the Object Tracking List (OTL) using
the QSYS2.CHANGE_RESYNC_ENTRIES procedure

V Generic versioning

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

ACTION VARCHAR(7) When ENTRY_TYPE is A, P, R, S, or U the type of resynchronization action to


performed:

INITIAL Initial synchronization of newly replicated objects.

RECLONE Resynchronization of actively replicating objects.

RESUME Resynchronization of objects that are on the OTL because the


node was previously blocked.

When ENTRY_TYPE is V:

ADD Register (add) an applied version information entry for a


specific feature or function in the Mirror Version List (MVL).

APPLY Apply pending version information entries.

REMOVE Unregister (remove) an applied version information entry from


the Mirror Version List (MVL).

REFRESH Refresh the version information entries in Mirror Version List


by running user specified version handlers.

Contains the null value if ENTRY_TYPE is D.

ACTION_DETAIL VARCHAR(200) Descriptive text that corresponds to the action.


Contains the null value if ACTION is null.

RULE_IDENTIFIER BIGINT Identifier for this replication criteria rule.


Contains the null value if ENTRY_TYPE is not A, D, or R.

INCLUSION_STATE VARCHAR(10) The inclusion state of the replication criteria rule.

DEFINITION Objects that best match this replication criteria rule are
replicated. Only the definition of the object is replicated.

EXCLUDE Objects that best match this replication criteria rule are not
replicated.

INCLUDE Objects that best match this replication criteria rule are
replicated.

Contains the null value if ENTRY_TYPE is not A or D.

Database performance and query optimization 731


Table 169. AUDIT_JOURNAL_M7 table function (continued)

Column Name Data Type Description

IASP_NAME VARCHAR(10) The name of the ASP group associated with this replication criteria
rule, the replicated object, or the SQL QSYS2.CHANGE_RESYNC_ENTRIES
procedure. Can contain the special value *SYSBAS.
Contains the null value if ENTRY_ TYPE is V.

LIBRARY_NAME VARCHAR(10) The library name associated with the replication criteria rule, the replicated
object, or the SQL QSYS2.CHANGE_RESYNC_ENTRIES procedure. Can
contain the special value *ALL.
Contains the null value if IASP_NAME is null.

OBJECT_TYPE VARCHAR(8) The object type associated with the replication criteria rule, the replicated
object, or the SQL QSYS2.CHANGE_RESYNC_ENTRIES procedure. Can
contain the special value *ALL.
Contains the null value if LIBRARY_NAME is null.

OBJECT_NAME VARCHAR(10) The name of the object associated with this replication criteria rule, the
replicated object, or the QSYS2.CHANGE_RESYNC_ENTRIES procedure.
Contains the null value if OBJECT_TYPE is null.

ORIGINAL_LIBRARY_NAME VARCHAR(10) Original library name.


Contains the null value if ENTRY_TYPE is not D.

SYSTEM_VALUE VARCHAR(10) The name of the system value associated with this replication criteria rule.
Contains the null value if ENTRY_TYPE is not A or R, or if OBJECT_NAME or
ENVIRONMENT_VARIABLE is not null.

ENVIRONMENT_VARIABLE VARCHAR(128) The name of the environment variable associated with this replication
criteria rule.
Contains the null value if ENTRY_TYPE is not A or R, or if OBJECT_NAME or
SYSTEM_VALUE is not null.

APPLY_LABEL VARCHAR(26) The label used to identify replication criteria rules.


Contains the null value if ENTRY_TYPE is D, S, or U.

NUMBER_OF_OBJECTS BIGINT The number of Save/Restore entries added to the OTL for objects affected
by this operation.
Contains the null value if ENTRY_TYPE is not A, P, R, or S.

AFFECTED_ROWS BIGINT The number of OTL rows affected by the SQL


QSYS2.CHANGE_RESYNC_ENTRIES procedure.
Contains the null value if ENTRY_TYPE is not U.

VERSION_ENTRY_NUMBER BIGINT The version entry number.


Contains the null value if ENTRY_TYPE is not V, or ENTRY_TYPE is V but
ACTION is not ADD or REMOVE.

VERSION_GROUP VARCHAR(10) The version group.


Contains the null value if ENTRY_TYPE is not V.

VERSION_NAME VARCHAR(30) The version name. Can contain the following special value:

*ALL All version names in VERSION_GROUP are operated on.

Contains the null value if ENTRY_TYPE is not V.

VERSION_IDENTIFIER VARCHAR(11) The version identifier. The format is xxx.yyy.zzz where each piece of the
version contains the digits 0-9:

xxx The major version number. This value is always present for a version
number.

yyy An optional minor version number.

zzz An optional revision number.

Contains the null value if ENTRY_TYPE is not V, or ENTRY_TYPE is V but


ACTION is not ADD or REMOVE.

732 IBM i: Performance and Query Optimization


Table 169. AUDIT_JOURNAL_M7 table function (continued)

Column Name Data Type Description

VERSION_ACTIVATION_TIME VARCHAR(9) The version entry activation state indicator.

IMMEDIATE This version entry can be activated immediately from an


applied state.

RESUME This version entry can be activated from an applied state


the next time replication is resumed.

Contains the null value if ENTRY_TYPE is not V, or ENTRY_TYPE is V but


ACTION is not ADD or REMOVE.

Example
• List any replication changes that affected APPLIB1 this week.

SELECT * FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_M7(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS
)
)
WHERE LIBRARY_NAME = 'APPLIB1';

AUDIT_JOURNAL_M8 table function


The AUDIT_JOURNAL_M8 table function returns rows from the audit journal that contain information from
the M8 (Db2 Mirror Product Services) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 170. AUDIT_JOURNAL_M8 table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the M8 audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Add IASP

C Change mirror

F Change flight recorder

H Change health monitor

I Set default inclusion state

J Change mirror ObjectConnect

L Reclone replicated objects

O Takeover

R Remove IASP

S Setup mirror

T Terminate mirror

W Swap mirror roles

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

Database performance and query optimization 733


Table 170. AUDIT_JOURNAL_M8 table function (continued)

Column Name Data Type Description

ACTION VARCHAR(15) Action to perform.


When ENTRY_TYPE is A:

NEW The IASP is being defined for the first time.

RECLONE The IASP is used as the source of a reclone operation.

SHADOW The IASP is being pre-defined as an IASP on a PowerHA®


disaster recovery system.

When ENTRY_TYPE is C:

RESUME Resume replication.

RESUMEABN Resume abnormal replication.

SUSPEND Suspend replication.

MAINTENANCE Suspend for maintenance.

When ENTRY_TYPE is F:

ENDJOB End flight recorder QMRDBLOGR job.

RESUME Resume flight recorder logging.

STARTJOB Start flight recorder QMRDBLOGR job.

SUSPEND Suspend flight recorder logging.

When ENTRY_TYPE is J:

CHANGE SERVER Change ObjectConnect for Db2 Mirror server.

END SERVER End ObjectConnect for Db2 Mirror server.

START SERVER Start ObjectConnect for Db2 Mirror server.

When ENTRY_TYPE is L:

RESUMEABN Reclone replicated objects with abnormal resume.

When ENTRY_TYPE is O:

ADD Add mirror takeover address.

CHANGE Change mirror takeover group.

CREATE Create mirror takeover group.

DELETE Delete mirror takeover group.

REMOVE Remove mirror takeover address.

SWAP Swap mirror takeover group.

When ENTRY_TYPE is T:

DESTROY Db2 Mirror is ended.

RECLONE Active replication is ended.

Contains the null value if:


• ENTRY_TYPE is not A, C, F, J, L, O, or T
• ENTRY_TYPE is C and the replication state was not specified
• ENTRY_TYPE is F and no action was specified
• ENTRY_TYPE is L and resume type was not specified

ACTION_DETAIL VARCHAR(200) Descriptive text that corresponds to the action.


Contains the null value if ACTION is null.

IASP_NAME VARCHAR(10) ASP name. Can contain the special value *SYSBAS.
Contains the null value if no ASP name applies to this entry.

734 IBM i: Performance and Query Optimization


Table 170. AUDIT_JOURNAL_M8 table function (continued)

Column Name Data Type Description

IASP_TYPE VARCHAR(8) The type of IASP.

DATABASE This IASP is for a database IASP group.

IFS This IASP is for an IFS ASP group.

Contains the null value if ENTRY_TYPE is not A or R.

DEFAULT_INCLUSION_STATE VARCHAR(7) When the ENTRY_TYPE is A, the default object inclusion state for objects in
IASP_NAME.
When ENTRY_TYPE is I, the default inclusion state for objects in *SYSBAS.

EXCLUDE Eligible objects not covered by an RCL rule will not be


replicated.

INCLUDE Eligible objects not covered by an RCL rule will be replicated.

RESET Clear the default inclusion state. This value applies when
ENTRY_TYPE is I.

Contains the null value if ENTRY_TYPE is not A or I.

CLUSTER_RESOURCE_GROUP VARCHAR(10) The cluster resource group name.


Contains the null value if ENTRY_TYPE is not A.

AUTO_RESUME VARCHAR(3) When ENTRY_TYPE is C, whether to automatically resume mirroring.

NO Do not automatically resume mirroring.

YES Automatically resume mirroring after being suspended.

Contains the null value if ENTRY_TYPE is not C or if the value was not
changed.

SWAP_ON_PWRDWNSYS VARCHAR(3) Swap behavior on power down system.

NO Do not automatically swap roles.

YES Automatically swap roles.

Contains the null value if ENTRY_TYPE is not C or if the value was not
changed.

PARALLEL_DEGREE VARCHAR(5) The degree of parallelism to be used for Db2 Mirror resynchronization
processing. Can contain the special value of NONE.
Contains the null value if ENTRY_TYPE is not C or if the value was not
changed.

SPLF_RESYNC_INTERVAL INTEGER The spooled file resynchronization interval.


Contains the null value if ENTRY_TYPE is not C or if the value was not
changed.

REPLICATE_USER_INDEX VARCHAR(7) The replication choice for user indexes.

DISABLE Disable replication of user indexes.

ENABLE Enable replication of user indexes.

Contains the null value if ENTRY_TYPE is not C or if the value was not
changed.

REPLICATE_USER_SPACE VARCHAR(7) The replication choice for user spaces.

DISABLE Disable replication of user spaces.

ENABLE Enable replication of user spaces.

Contains the null value if ENTRY_TYPE is not C or if the value was not
changed.

REPLICATE_DATA_QUEUE_ENTRIES VARCHAR(7) The replication choice for entries in a data queue (*DTAQ).

DISABLE Disable replication of data queue entries.

ENABLE Enable replication of data queue entries.

Contains the null value if ENTRY_TYPE is not C or if the value was not
changed.

Database performance and query optimization 735


Table 170. AUDIT_JOURNAL_M8 table function (continued)

Column Name Data Type Description

ENCRYPTED_RDMA VARCHAR(12) The encrypted RDMA value.

NOT REQUIRED Non-encrypted RDMA protocols may be used.

REQUIRED Encrypted RDMA protocols must be used.

Contains the null value if ENTRY_TYPE is not C or if the value was not
changed.

AUTO_TAKEOVER VARCHAR(7) The choice for automatic takeover for unplanned outages.

DISABLE Disable automatic takeover for unplanned outages.

ENABLE Enable automatic takeover for unplanned outages.

Contains the null value if ENTRY_TYPE is not C or if the value was not
changed.

TAKEOVER_GROUP_NAME VARCHAR(10) The takeover group name.


Contains the null value if ENTRY_TYPE is not O.

AUTO_SWITCHBACK VARCHAR(3) When ENTRY_TYPE is O and ACTION is CREATE or CHANGE, whether the
takeover IP address group should be automatically switched back to its
preferred node.

NO Do not automatically return this takeover IP address group.

YES Automatically return this takeover IP address group to its preferred


node.

Contains the null value if ENTRY_TYPE is not O or if the value was not
changed.

PRIMARY_NODE VARCHAR(8) When ENTRY_TYPE is O and ACTION is CREATE or CHANGE, the name of the
preferred node.
When ENTRY_TYPE is S or T, the name of the partition designated as the
primary node.
When ENTRY_TYPE is W, the name of the new primary node.
Contains the null value if ENTRY_TYPE is not O, S, T, or W.

SECONDARY_NODE VARCHAR(8) The name of the partition designated as the secondary node.
When ENTRY_TYPE is W this is the name of the new secondary node.
Contains the null value if ENTRY_TYPE is not S, T, or W.

IP_ADDRESS VARCHAR(45) The takeover IP address.


Contains the null value if ENTRY_TYPE is not O and ACTION is not ADD or
REMOVE.

OBJECTCONNECT_AUTO_START VARCHAR(3) Whether to automatically start the ObjectConnect for Db2 Mirror server.

NO Do not automatically start the ObjectConnect for Db2 Mirror server.

YES Automatically start the ObjectConnect for Db2 Mirror server.

Contains the null value if ENTRY_TYPE is not J or if the value was not
changed.

OBJECTCONNECT_MINIMUM_JOBS INTEGER The minimum number of ObjectConnect for Db2 Mirror server jobs that are
started.
Contains the null value if ENTRY_TYPE is not J or if the value was not
changed.

OBJECTCONNECT_MAXIMUM_JOBS INTEGER The maximum number of ObjectConnect for Db2 Mirror server jobs that are
started.
Contains the null value if ENTRY_TYPE is not J or if the value was not
changed.

OBJECTCONNECT_INACTIVE_TIME INTEGER The length of time, in minutes, that a ObjectConnect for Db2 Mirror server
job will stay inactive before ending.
Contains the null value if ENTRY_TYPE is not J or if the value was not
changed.

ARCHIVE_RETENTION_DAY_COUNT INTEGER The number of days the flight recorder logs are retained.
Contains the null value if ENTRY_TYPE is not F.

736 IBM i: Performance and Query Optimization


Table 170. AUDIT_JOURNAL_M8 table function (continued)

Column Name Data Type Description

MAX_SYSBAS_PERCENTAGE INTEGER The percentage of *SYSBAS allocated for flight recorder logs.
Contains the null value if ENTRY_TYPE is not F.

LOGGING_CATEGORY VARCHAR(26) The category for which flight recorder entries will be logged.

ALL All categories

CONFIGURATION PROCESSING Configuration processing

DATABASE Database processing

DATA QUEUE Data queue handler

DB CONNECTION Database connection

ENGINE COMMUNICATION Engine communication

ENGINE CONNECTION Engine connection

ENGINE CONTROLLER Engine controller

ENGINE JOB Engine job

ENGINE STATE Engine state

FLIGHT RECORDER Flight recorder

HEALTH MONITOR Health monitor

IFS CONNECTION IFS connection

LOGGER TESTING Logger testing

NRG Network redundancy groups

OBJECT CONNECTION Object connection

OBJECT RECEIVER Object receiver

OBJECT REGISTRY Object registry

OBJECT REPLICATION MANAGER Object replication manager

OBJECT SYNCHRONIZATION Object synchronization

QUORUM SERVER Quorum server

RCL Replication criteria list

RESYNC Resynchronization process

SAVE RESTORE Save and restore processing

SECURITY OBJECT Security object handler

SPOOL Spooled file handler

OUTPUT AND JOB QUEUE Output queue and job queue


processing

UTILITIES Utilities processing

VARY IASP Vary IASP processing

WORK MANAGEMENT Work management

Contains the null value if ENTRY_TYPE is not F.

Database performance and query optimization 737


Table 170. AUDIT_JOURNAL_M8 table function (continued)

Column Name Data Type Description

LOGGING_LEVEL VARCHAR(7) The level at which an entry is written to the flight recorder log.

DEBUG Log entries for the INFO level are generated, plus debug
information.

ERROR Log entries are generated for run time errors and unexpected
conditions.

INFO Log entries for the WARN level are generated, plus
interesting run time events.

NONE No log entries are generated.

SYSTEM When LOGGING_CATEGORY is ALL the shipped default level


is set for each category.

WARNING Log entries for the ERROR level are generated, plus entries
for errors or other run time situations that are unexpected or
unusual but not necessarily wrong.

Contains the null value if ENTRY_TYPE is not F.

Example
• List when Db2 Mirror active replication was suspended in the last 2 months.

SELECT * FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_M8(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 2 MONTHS
)
)
WHERE ENTRY_TYPE = 'C' AND
ACTION IN ('SUSPEND', 'MAINTENANCE');

AUDIT_JOURNAL_M9 table function


The AUDIT_JOURNAL_M9 table function returns rows from the audit journal that contain information from
the M9 (Db2 Mirror Replication State) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 171. AUDIT_JOURNAL_M9 table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the M9 audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

C Change to the replication state of an ASP

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

IASP_NAME VARCHAR(10) ASP name for which the replication state changed. Can contain the special
value *SYSBAS.

REPLICATION_STATE VARCHAR(12) Db2 Mirror replication state.

ACTIVE

BLOCKED

NOT MIRRORED

TRACKING

738 IBM i: Performance and Query Optimization


Table 171. AUDIT_JOURNAL_M9 table function (continued)

Column Name Data Type Description

PREVIOUS_REPLICATION_STATE VARCHAR(12) Previous Db2 Mirror replication state.

ACTIVE

BLOCKED

NOT MIRRORED

TRACKING

CHANGE_REASON INTEGER The reason code corresponding to the replication state change. See
Replication detail info for the list of reason codes.
Contains the null value when REPLICATION_STATE or
PREVIOUS_REPLICATION_STATE is NOT MIRRORED.

CHANGE_REASON_DETAIL VARCHAR(200) Descriptive text that corresponds to the reason code.


Contains the null value when REPLICATION_STATE or
PREVIOUS_REPLICATION_STATE is NOT MIRRORED.

Example
• List any reasons that IASP1 suspended replication in the past 24 hours.

SELECT ENTRY_TIMESTAMP, IASP_NAME, REPLICATION_STATE, CHANGE_REASON_DETAIL


FROM TABLE(
SYSTOOLS.AUDIT_JOURNAL_M9(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 24 HOURS )
)
WHERE REPLICATION_STATE <> 'ACTIVE' AND IASP_NAME = 'IASP1'
ORDER BY ENTRY_TIMESTAMP DESC;

AUDIT_JOURNAL_NA table function


The AUDIT_JOURNAL_NA table function returns rows from the audit journal that contain information from
the NA (Attribute Change) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 172. AUDIT_JOURNAL_NA table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the NA audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Change to a network attribute

T Change to a TCP/IP attribute

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

ATTRIBUTE_NAME VARCHAR(10) The name of the attribute.

ATTRIBUTE_VALUE VARCHAR(250) The value of the attribute.

PREV_ATTRIBUTE_VALUE VARCHAR(250) The previous value of the attribute.

Example
• List the TCP/IP attributes that were changed in the last two months.

SELECT * FROM TABLE(

Database performance and query optimization 739


SYSTOOLS.AUDIT_JOURNAL_NA(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 2 MONTHS
)
)
WHERE ENTRY_TYPE = 'T';

AUDIT_JOURNAL_OM table function


The AUDIT_JOURNAL_OM table function returns rows from the audit journal that contain information from
the OM (Object Management Change) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 173. AUDIT_JOURNAL_OM table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the OM audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

M Object moved to a different library.

R Object renamed.

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

LIBRARY_NAME VARCHAR(10) The name of the library to which the object was moved.
Contains the null value if there is no new library name.

OBJECT_NAME VARCHAR(10) The new name of the object which was moved.
Contains the null value if there is no new object name.

OBJECT_TYPE VARCHAR(7) The type of object.


Contains the null value if there is no object type.

OBJECT_ATTRIBUTE VARCHAR(10) The attribute of the object.


Contains the null value if there is no object attribute.

PREV_LIBRARY_NAME VARCHAR(10) The name of the library in which the previous object resides.
Contains the null value if there is no previous library name.

PREV_OBJECT_NAME VARCHAR(10) The previous name of the object.


Contains the null value if there is no previous object name.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object
resides. If the new object is in a library, this is the ASP information
of the object's library. If the new object is not in a library, this is
the ASP information of the object. A value of *SYSBAS indicates the
system ASP and all basic user ASPs.
Contains the null value if there is no ASP information.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device. If the new object is in a library, this
is the ASP information of the object's library. If the new object is not
in a library, this is the ASP information of the object.
Contains the null value if there is no ASP information.

PREV_OBJECT_ASP_NAME VARCHAR(10) The previous name of the auxiliary storage pool (ASP) in which the
object resides. If the previous object is in a library, this is the ASP
information of the object's library. If the previous object is not in a
library, this is the ASP information of the object. A value of *SYSBAS
indicates the system ASP and all basic user ASPs.
Contains the null value if there is no ASP information.

740 IBM i: Performance and Query Optimization


Table 173. AUDIT_JOURNAL_OM table function (continued)

Column Name Data Type Description

PREV_OBJECT_ASP_NUMBER INTEGER The previous number of the ASP device. If the previous object is in
a library, this is the ASP information of the object's library. If the
previous object is not in a library, this is the ASP information of the
object.
Contains the null value if there is no ASP information.

PATH_NAME VARGRAPHIC(5000) CCSID 1200 The new path name of the object.
Contains the null value if the path name is not available or the
object is not in the "root" (/), QOpenSys, or user-defined file
systems.

PATH_NAME_INDICATOR VARCHAR(3) New path name indicator:

NO The PATH_NAME column does not contain an absolute path


name for the object, instead it contains a relative path
name. The RELATIVE_DIRECTORY_FILE_ID can be used to
form an absolute path name with this relative path name.

YES The PATH_NAME column contains the absolute path name


for the object.

Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the


directory that contains the object identified in the PATH_NAME
column.
Contains the null value when PATH_NAME_INDICATOR is YES, or
if the file ID is not available or the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) CCSID 1200 The name of the new object.


Contains the null value if the object name is not available or
the object is not in the "root" (/), QOpenSys, or user-defined file
systems.

OBJECT_FILE_ID BINARY(16) The file ID of the new object.


Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the new parent directory.


Contains the null value if the file ID is not available or the object is
not in the "root" (/), QOpenSys, or user-defined file systems.

PREV_PATH_NAME VARGRAPHIC(5000) CCSID 1200 The previous path name of the object.
Contains the null value if the path name is not available or the
object is not in the "root" (/), QOpenSys, or user-defined file
systems.

PREV_PATH_NAME_INDICATOR VARCHAR(3) Previous path name indicator:

NO The PREV_PATH_NAME column does not contain


an absolute path name for the object,
instead it contains a relative path name. The
PREV_RELATIVE_DIRECTORY_FILE_ID can be used to form
an absolute path name with this relative path name.

YES The PREV_PATH_NAME column contains the absolute path


name for the object.

Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PREV_RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PREV_PATH_NAME_INDICATOR is NO, contains the file


ID of the directory that contains the object identified in the
PREV_PATH_NAME column.
Contains the null value when PREV_PATH_NAME_INDICATOR is
YES, or if the file ID is not available or the object is not in the "root"
(/), QOpenSys, or user-defined file systems.

PREV_IFS_OBJECT_NAME VARGRAPHIC(512) CCSID 1200 The name of the previous object.


Contains the null value if the object name is not available or
the object is not in the "root" (/), QOpenSys, or user-defined file
systems.

Database performance and query optimization 741


Table 173. AUDIT_JOURNAL_OM table function (continued)

Column Name Data Type Description

PREV_OBJECT_FILE_ID BINARY(16) The file ID of the previous object.


Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PREV_PARENT_FILE_ID BINARY(16) The file ID of the previous parent directory.


Contains the null value if the file ID is not available or the object is
not in the "root" (/), QOpenSys, or user-defined file systems.

OFFICE_USER VARCHAR(10) The name of the office user.


Contains the null value if there is no office user.

OFFICE_ON_BEHALF_OF_USER VARCHAR(10) User working on behalf of another user.


Contains the null value if there is no user name.

DLO_NAME VARCHAR(12) The new name of the folder or document.


Contains the null value if there is no new folder or document.

FOLDER_PATH VARCHAR(63) The new path of the folder.


Contains the null value if there is no new folder path.

PREV_DLO_NAME VARCHAR(12) The previous name of the folder or document.


Contains the null value if there is no previous folder or document.

PREV_FOLDER_PATH VARCHAR(63) The previous path of the folder.


Contains the null value if there is no previous folder path.

Example
• List any objects that were moved or renamed in the APPLIB library this week.

SELECT LIBRARY_NAME, OBJECT_NAME, PREV_LIBRARY_NAME, PREV_OBJECT_NAME, OBJECT_TYPE


FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_OM (STARTING_TIMESTAMP => CURRENT DATE - 7 DAYS)
)
WHERE PREV_LIBRARY_NAME = 'APPLIB';

AUDIT_JOURNAL_OR table function


The AUDIT_JOURNAL_OR table function returns rows from the audit journal that contain information from
the OR (Object Restore) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 174. AUDIT_JOURNAL_OR table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the OR audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

E An existing object was restored to the system.

N A new object was restored to the system.

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

OBJECT_LIBRARY VARCHAR(10) The name of the library containing the restored object.
Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) The name of the restored object.


Contains the null value if there is no object name.

742 IBM i: Performance and Query Optimization


Table 174. AUDIT_JOURNAL_OR table function (continued)

Column Name Data Type Description

OBJECT_TYPE VARCHAR(7) The type of object.


Contains the null value if there is no object type.

OBJECT_ATTRIBUTE VARCHAR(10) The attribute of the object.


Contains the null value if there is no object attribute.

SAVE_OBJECT_LIBRARY VARCHAR(10) The name of the library from which the object was saved.
Contains the null value if there is no saved library name.

SAVE_OBJECT VARCHAR(10) The name of the saved object.


Contains the null value if there is no saved object name.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object
resides. A value of *SYSBAS indicates the system ASP and all basic
user ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.

PROGRAM_STATE VARCHAR(8) The state of the program that was restored.

*INHERIT An inherit state program was restored.

*SYSTEM A system state program was restored.

*USER A user state program was restored.

Contains the null value if OBJECT_TYPE is not *PGM or *SRVPGM.

COMMAND_STATE VARCHAR(7) Whether the command is a system command.

*SYSTEM A system command was restored.

*USER A user state command was restored.

Contains the null value if OBJECT_TYPE is not *CMD.

SAVE_SYSTEM VARCHAR(8) The system from which the object was saved.
Contains the null value if the system from which the object was
saved was running a release prior to IBM i 7.1, or if a value is not
available.

RESTORE_PRIVATE_AUTHORITIES VARCHAR(3) Private authorities requested to be restored.

YES Private authorities (PVTAUT) was specified as *YES on the


restore command.

NO Private authorities (PVTAUT) was specified as *NO on the


restore command.

PRIVATE_AUTHORITIES_SAVED INTEGER Number of private authorities saved.

PRIVATE_AUTHORITIES_RESTORED INTEGER Number of private authorities restored.

SIGNATURE_STATUS VARCHAR(12) The signature status of the restored object.

IGNORED Signature ignored

NOT SIGNABLE Unsignable object

NOT TRUSTED Untrusted signature

NOT VERIFIED Signature exists but is not verified

UNMATCHED Signature does not match object content

VALID Signature is valid

WRONG FORMAT Signature was not in IBM i format

Contains the null value if a value is not available.

PATH_NAME VARGRAPHIC(5000) CCSID 1200 The path name of the object.


Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

Database performance and query optimization 743


Table 174. AUDIT_JOURNAL_OR table function (continued)

Column Name Data Type Description

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path


name for the object, instead it contains a relative path
name. The RELATIVE_DIRECTORY_FILE_ID can be used to
form an absolute path name with this relative path name.

YES The PATH_NAME column contains complete absolute path


name for the object.

Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the


directory that contains the object identified in the PATH_NAME
column.
Contains the null value when PATH_NAME_INDICATOR is YES, or
if the object is not in the "root" (/), QOpenSys, or user-defined file
systems.

IFS_OBJECT_NAME VARGRAPHIC(512) CCSID 1200 The name of the object.


Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PREV_OBJECT_FILE_ID BINARY(16) The file ID of the object that was replaced on the restore.
Contains the null value if the object did not exist prior to the restore
or is not in the "root" (/), QOpenSys, or user-defined file systems.

SAVE_OBJECT_FILE_ID BINARY(16) The file ID (FID) of the saved object. This is the FID the object had
on the save system.
Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

EXIT_PROGRAM_SCAN VARCHAR(11) Whether the object will be scanned when exit programs are
registered with any of the integrated file system scan-related exit
points.

CHANGE The object will be scanned according to the rules


ONLY described in the scan-related exit programs only if
the object has been modified since the last time the
object was scanned. It will not be scanned if the
scanning software has been updated. This attribute
only takes effect if the Scan file systems control
(QSCANFSCTL) system value has *USEOCOATR
specified. Otherwise, it will be treated the same as
YES.

NO The object will not be scanned according to the rules


described in the scan-related exit programs.

YES The object will be scanned according to the rules


described in the scan-related exit programs if the
object has been modified or if the scanning software
has been updated since the last time the object was
scanned.

Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

SET_EFFECTIVE_USER_ID VARCHAR(3) The set effective user ID (SETUID) mode indicator for the restored
object.

NO The SETUID mode bit is not on.

YES The SETUID mode bit is on.

Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

744 IBM i: Performance and Query Optimization


Table 174. AUDIT_JOURNAL_OR table function (continued)

Column Name Data Type Description

SET_EFFECTIVE_GROUP_ID VARCHAR(3) The set effective group ID (SETGID) mode indicator for the restored
object.

NO The SETGID mode bit is not on.

YES The SETGID mode bit is on.

Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

OFFICE_USER VARCHAR(10) The name of the office user.


Contains the null value if a value is not available.

OFFICE_ON_BEHALF_OF_USER VARCHAR(10) User working on behalf of another user.


Contains the null value if a value is not available.

DLO_NAME VARCHAR(12) The name of the restored document library object.


Contains the null value if there is no document library object.

FOLDER_PATH VARCHAR(63) The folder into which the document library object was restored.
Contains the null value if there is no folder path.

SAVED_DLO_NAME VARCHAR(12) The name of the saved document library object.


Contains the null value if there is no saved document library object.

SAVED_FOLDER_PATH VARCHAR(63) The folder from which the document library object was saved.
Contains the null value if there is no saved folder path.

Example
• List objects that were restored into APPLIB this week.

SELECT OBJECT_NAME, OBJECT_TYPE


FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_OR (STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS)
)
WHERE OBJECT_LIBRARY = 'APPLIB';

AUDIT_JOURNAL_OW table function


The AUDIT_JOURNAL_OW table function returns rows from the audit journal that contain information
from the OW (Ownership Change) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 175. AUDIT_JOURNAL_OW table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the OW audit journal entry.

OBJECT_LIBRARY VARCHAR(10) The name of the library where the object is stored.

OBJECT_NAME VARCHAR(10) The name of the object.

OBJECT_TYPE VARCHAR(7) The type of object.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object resides. A
value of *SYSBAS indicates the system ASP and all basic user ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.

PREVIOUS_OWNER VARCHAR(10) Previous owner of the object.

NEW_OWNER VARCHAR(10) New owner of the object.

Database performance and query optimization 745


Table 175. AUDIT_JOURNAL_OW table function (continued)

Column Name Data Type Description

PATH_NAME VARGRAPHIC(5000) The path name of the object.


CCSID 1200
Contains the null value if the object name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path name


for the object, instead it contains a relative path name. The
RELATIVE_DIRECTORY_FILE_ID can be used to form an absolute
path name with this relative path name.

YES The PATH_NAME column contains complete absolute path name for
the object.

Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the directory
that contains the object identified in the PATH_NAME column.
Contains the null value when PATH_NAME_INDICATOR is YES, or if the
file ID is not available or the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) The name of the object.


CCSID 1200
Contains the null value if the object name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the object is not in the
"root" (/), QOpenSys, or user-defined file systems.

OFFICE_USER VARCHAR(10) The name of the office user.

OFFICE_ON_BEHALF_OF_USER VARCHAR(10) User working on behalf of another user.

DLO_NAME VARCHAR(12) The name of the document library object.

FOLDER_PATH VARCHAR(63) The path of the folder.

Example
• List the objects in APPLIB1 or APPLIB2 that had object ownership changes in the last 3 months.

SELECT *
FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_OW (STARTING_TIMESTAMP => CURRENT TIMESTAMP - 3 MONTHS)
)
WHERE OBJECT_LIBRARY IN ('APPLIB1', 'APPLIB2');

AUDIT_JOURNAL_PA table function


The AUDIT_JOURNAL_PA table function returns rows from the audit journal that contain information from
the PA (Program Adopt) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 176. AUDIT_JOURNAL_PA table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the PA audit journal entry.

746 IBM i: Performance and Query Optimization


Table 176. AUDIT_JOURNAL_PA table function (continued)

Column Name Data Type Description

ENTRY_TYPE CHAR(1) The type of entry.

A Change program to adopt owner's authority.

J Java program adopts owner's authority.

M Change object's SETUID, SETGID, or restricted rename and unlink


mode indicator.

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

OBJECT_LIBRARY VARCHAR(10) The name of the library containing the program.


Contains the null value if ENTRY_TYPE is J or if there is no library name.

OBJECT_NAME VARCHAR(10) The name of the program.


Contains the null value if ENTRY_TYPE is J or if there is no program name.

OBJECT_TYPE VARCHAR(7) The type of the object.


Contains the null value if there is no object type.

OBJECT_OWNER VARCHAR(10) The owner of the object.


Contains the null value if there is no object owner.

PRIMARY_GROUP VARCHAR(10) The name of the primary group.


Contains the null value if there is no primary group.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object resides. A
value of *SYSBAS indicates the system ASP and all basic user ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.

PATH_NAME VARGRAPHIC(5000) The path name of the object.


CCSID 1200
Contains the null value if the path name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path name


for the object, instead it contains a relative path name. The
RELATIVE_DIRECTORY_FILE_ID can be used to form an absolute
path name with this relative path name.

YES The PATH_NAME column contains complete absolute path name for
the object.

Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the directory
that contains the object identified in the PATH_NAME column.
Contains the null value when PATH_NAME_INDICATOR is YES, or if the
file ID is not available or the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) The name of the object.


CCSID 1200
Contains the null value if the object name is not available or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/), QOpenSys, or
user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the object is not in the
"root" (/), QOpenSys, or user-defined file systems.

SET_EFFECTIVE_USER_ID VARCHAR(3) The current set effective user ID (SETUID) mode indicator.

NO The SETUID mode bit is not on for the object.

YES The SETUID mode bit is on for the object.

Contains the null value if the information is not available.

Database performance and query optimization 747


Table 176. AUDIT_JOURNAL_PA table function (continued)

Column Name Data Type Description

SET_EFFECTIVE_GROUP_ID VARCHAR(3) The current set effective group ID (SETGID) mode indicator.

NO The SETGID mode bit is not on for the object.

YES The SETGID mode bit is on for the object.

Contains the null value if the information is not available.

RESTRICT_RENAME_AND_UNLINK VARCHAR(3) The current restricted rename and unlink (ISVTX) mode indicator.

NO The ISVTX mode bit is not on for the object.

YES The ISVTX mode bit is on for the object.

Contains the null value if the information is not available.

PREV_SET_EFFECTIVE_USER_ID VARCHAR(3) The previous set effective user ID (SETUID) mode indicator.

NO The SETUID mode bit was not on for the object.

YES The SETUID mode bit was on for the object.

Contains the null value if the information is not available.

PREV_SET_EFFECTIVE_GROUP_ID VARCHAR(3) The previous set effective group ID (SETGID) mode indicator.

NO The SETGID mode bit was not on for the object.

YES The SETGID mode bit was on for the object.

Contains the null value if the information is not available.

PREV_RESTRICT_RENAME_ VARCHAR(3) The previous restricted rename and unlink (ISVTX) mode indicator.
AND_UNLINK
NO The ISVTX mode bit was not on for the object.

YES The ISVTX mode bit was on for the object.

Contains the null value if the information is not available.

Example
• Find any programs that were changed to adopt the program owner's authority in the last month.

SELECT OBJECT_LIBRARY, OBJECT_NAME, OBJECT_TYPE, OBJECT_OWNER FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_PA(
STARTING_TIMESTAMP => CURRENT DATE - 1 MONTH
)
) WHERE ENTRY_TYPE = 'A';

AUDIT_JOURNAL_PF table function


The AUDIT_JOURNAL_PF table function returns rows from the audit journal that contain information from
the PF (PTF Operations) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 177. AUDIT_JOURNAL_PF table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the PF audit journal entry.

748 IBM i: Performance and Query Optimization


Table 177. AUDIT_JOURNAL_PF table function (continued)

Column Name Data Type Description

ENTRY_TYPE CHAR(1) The type of entry.

I PTF IPL operation

L PTF product(s) operation

P PTF operations

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

ENTRY_ACTION VARCHAR(4) The type of action.


When ENTRY_TYPE is I:

IPLA Attended IPL performed

IPLU Unattended IPL performed

When ENTRY_TYPE is L:

DELT Product deleted

GOPT GO PTF option 7 (Install a program temporary fix from a


list) or 8 (Install program temporary fix package) invoked

INSP INSPTF command invoked

REST Product restored/installed

SAVE Product saved

SYNC User called QPZSYNC

When ENTRY_TYPE is P:

DAMG PTF damaged

EXTE PTF exit program ended

EXTS PTF exit program started

LOAD PTF loaded

LOGF PTF logged

PAPY PTF permanently applied

PDLT PTF deleted

PRMV PTF permanently removed

SUPR PTF superseded

TAPY PTF temporarily applied

TRMV PTF temporarily removed

ENTRY_ACTION_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry action.

PRODUCT_ID VARCHAR(7) Product identifier. Can contain one of the following special values:

*ALL All products

*FMW Firmware

*LIST List of products

Contains the null value if ENTRY_TYPE is I.

PRODUCT_RELEASE_LEVEL VARCHAR(6) Product version, release, modification in format VvRrMm or *ONLY.


Contains the null value if ENTRY_TYPE is I.

PTF_IDENTIFIER VARCHAR(7) PTF identifier.


Contains the null value if ENTRY_TYPE is I or L.

PRODUCT_OPTION VARCHAR(4) Product option or *ALL.


Contains the null value if ENTRY_TYPE is I, or ENTRY_TYPE is P or L
and a value is not available.

LOAD_ID VARCHAR(4) Product load identifier or *ALL.


Contains the null value if ENTRY_TYPE is I, or ENTRY_TYPE is P or L
and a value is not available.

Database performance and query optimization 749


Table 177. AUDIT_JOURNAL_PF table function (continued)

Column Name Data Type Description

PRODUCT_MINIMUM_LEVEL VARCHAR(2) Product minimum level.


Contains the null value if ENTRY_TYPE is I, or ENTRY_TYPE is P or L
and a value is not available.

PRODUCT_MAXIMUM_LEVEL VARCHAR(2) Product maximum level.


Contains the null value if ENTRY_TYPE is I, or ENTRY_TYPE is P or L
and a value is not available.

PRODUCT_LIBRARY VARCHAR(10) Product library. Can contain one of the following special values.

*ALL All product libraries

*FMW Firmware

Contains the null value if ENTRY_TYPE is I, or ENTRY_TYPE is P or L


and a value is not available.

ACTION_PENDING VARCHAR(3) Action pending for PTF.

NO No action pending for PTF

YES Action pending for PTF

Contains the null value if ENTRY_TYPE is not P, or ENTRY_TYPE is P


and ENTRY_ACTION is EXTE or EXTS.

IPL_ACTION VARCHAR(25) Action to take for PTF on the next IPL.

APPLY PERMANENTLY Apply permanently at IPL

APPLY PERMANENTLY AT Apply temporarily, and then


IPL permanently at IPL

APPLY TEMPORARILY Apply temporarily at IPL

NONE No IPL action taken

REMOVE PERMANENTLY Remove permanently at IPL

REMOVE PERMANENTLY AT Remove temporarily, and then


IPL permanently at IPL

REMOVE TEMPORARILY Remove temporarily at IPL

Contains the null value if ENTRY_TYPE is not P, or ENTRY_TYPE is P


and ENTRY_ACTION is EXTE or EXTS.

EXIT_PROGRAM_LIBRARY VARCHAR(10) The library in which EXIT_PROGRAM resides.


Contains the null value if ENTRY_TYPE is not P with an
ENTRY_ACTION of EXTE or EXTS.

EXIT_PROGRAM VARCHAR(10) The name of the PTF exit program.


Contains the null value if ENTRY_TYPE is not P with an
ENTRY_ACTION of EXTE or EXTS.

EXIT_PROGRAM_ACTION VARCHAR(21) The PTF exit program action.

APPLY PERMANENTLY Apply permanently

APPLY TEMPORARILY Apply temporarily

PREAPPLY PERMANENTLY Pre-apply permanently

PREAPPLY TEMPORARILY Pre-apply temporarily

PREREMOVE PERMANENTLY Pre-remove permanently

PREREMOVE TEMPORARILY Pre-remove temporarily

REMOVE PERMANENTLY Remove permanently

REMOVE TEMPORARILY Remove temporarily

Contains the null value if ENTRY_TYPE is not P with an


ENTRY_ACTION of EXTE or EXTS.

SUPERSEDED_BY_PTF VARCHAR(7) Superseded-by PTF identifier.


Contains the null value if ENTRY_TYPE is not P with an
ENTRY_ACTION of SUPR.

750 IBM i: Performance and Query Optimization


Table 177. AUDIT_JOURNAL_PF table function (continued)

Column Name Data Type Description

APPLY_TYPE VARCHAR(8) PTF install apply type.

*DLYALL Mark PTFs for delayed apply

*DLYIPL Mark PTFs for delayed apply and IPL

*IMMDLY Apply immediate PTFs and mark delayed PTFS for


delayed apply

*IMMONLY Only apply immediate PTFs

Contains the null value if ENTRY_TYPE is not L with an


ENTRY_ACTION of GOPT or INSP.

DEVICE_NAME VARCHAR(10) PTF install device name. Can contain one of the following special
values:

*NONE No PTFs are loaded, PTFs already loaded are applied

*SERVICE Install PTFs received from service support system

Contains the null value if ENTRY_TYPE is not L with an


ENTRY_ACTION of GOPT or INSP.

IMAGE_CATALOG VARCHAR(10) PTF install image catalog name. Can contain one of the following
special values:

*NETOPT Network Optical

*NONE No image catalog

*RMTDEV Remote device

Contains the null value if ENTRY_TYPE is not L with an


ENTRY_ACTION of GOPT or INSP.

MEDIA_PROMPT VARCHAR(10) PTF install prompt for media.

*MLTSRV Prompt for volumes in multiple volume sets then


load from *SERVICE

*MLTVOLSET Prompt for volumes in multiple volume sets

*SNGVOLSET Prompt for volumes in single volume set

Contains the null value if ENTRY_TYPE is not L with an


ENTRY_ACTION of GOPT or INSP.

HIPER_PTFS VARCHAR(3) Only HIPER PTFs loaded on PTF install.

NO All PTFs loaded.

YES Only HIPER PTFs loaded

Contains the null value if ENTRY_TYPE is not L with an


ENTRY_ACTION of GOPT or INSP.

COPY_SERVICE_PTFS VARCHAR(3) Copy PTF save files and cover letters into *SERVICE on PTF install.

NO PTFs not copied

YES PTFs copied

Contains the null value if ENTRY_TYPE is not L with an


ENTRY_ACTION of GOPT or INSP.

OMIT_PTFS VARCHAR(3) PTFs omitted on PTF install.

NO Ftps were not omitted

YES PTFs were omitted

Contains the null value if ENTRY_TYPE is not L with an


ENTRY_ACTION of GOPT or INSP.

Database performance and query optimization 751


Table 177. AUDIT_JOURNAL_PF table function (continued)

Column Name Data Type Description

AUTOMATIC_IPL VARCHAR(3) Automatic IPL on PTF install.

NO No automatic IPL

YES Automatic IPL performed

Contains the null value if ENTRY_TYPE is not L with an


ENTRY_ACTION of GOPT or INSP.

IPL_RESTART_TYPE VARCHAR(5) IPL restart type for automatic IPL on PTF install.

IPLA IPL attributes

*FULL All parts of system, including hardware, are restarted

*SYS System determines how much to restart

Contains the null value if AUTOMATIC_IPL is not YES.

QPZSYNC_PARAMETER CHAR(1) First parameter passed to QPZSYNC.


Contains the null value if ENTRY_TYPE is not L with an
ENTRY_ACTION of SYNC.

IPL_TYPE VARCHAR(10) IPL type.

UNATTENDED Unattended IPL

ATTENDED Attended IPL

INSTALL IPL during operating system install

Contains the null value if ENTRY_TYPE is not I.

ABNORMAL_IPL VARCHAR(3) Abnormal IPL.

NO Normal IPL

YES Abnormal IPL

Contains the null value if ENTRY_TYPE is not I.

LIC_RESTORED VARCHAR(3) LIC restored during this IPL.

NO LIC not restored

YES LIC restored

Contains the null value if ENTRY_TYPE is not I.

LIC_IPL_REQUESTED VARCHAR(3) Re-IPL of LIC requested during IPL.

NO No re-IPL of LIC requested

YES Re-IPL of LIC requested

Contains the null value if ENTRY_TYPE is not I.

RESTART_SHARED_ACTIVATION_GROU VARCHAR(3) Restart Shared Activation Group (SAG) during IPL after applying
P PTFs.

NO SAG not restarted

YES SAG restarted

Contains the null value if ENTRY_TYPE is not I.

Example
• For each PTF action that has been performed today, list the number of times it occurred along with the
description of the action.

SELECT COUNT(*) AS ACTION_COUNT, ENTRY_ACTION, MIN(ENTRY_ACTION_DETAIL)


FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_PF (STARTING_TIMESTAMP => CURRENT DATE)
)
WHERE ENTRY_TYPE = 'P'
GROUP BY ENTRY_ACTION

752 IBM i: Performance and Query Optimization


ORDER BY ACTION_COUNT;

AUDIT_JOURNAL_PG table function


The AUDIT_JOURNAL_PG table function returns rows from the audit journal that contain information from
the PG (Primary Group Change) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 178. AUDIT_JOURNAL_PG table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the PG audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Change primary group.

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

PRIMARY_GROUP VARCHAR(10) The new primary group for the object.

PREV_PRIMARY_GROUP VARCHAR(10) The previous primary group for the object.


Contains the null value if the previous primary group is not
available.

REVOKE_PREV_PRIMARY_GROUP VARCHAR(3) Indicates whether authority was revoked for the previous primary
group.

NO Authority was not revoked for previous primary group.

YES Authority was revoked for previous primary group.

LIBRARY_NAME VARCHAR(10) The name of the library containing the object.


Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) The name of the object.


Contains the null value if there is no object name.

OBJECT_TYPE VARCHAR(7) The type of object.


Contains the null value if there is no object type.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object
resides. A value of *SYSBAS indicates the system ASP and all basic
user ASPs.
Contains the null value if there is no ASP information.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.


Contains the null value if there is no ASP information.

PATH_NAME VARGRAPHIC(5000) CCSID 1200 The path name of the object.


Contains the null value if the path name is not available or the
object is not in the "root" (/), QOpenSys, or user-defined file
systems.

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator:

NO The PATH_NAME column does not contain an absolute path


name for the object, instead it contains a relative path
name. The RELATIVE_DIRECTORY_FILE_ID can be used to
form an absolute path name with this relative path name.

YES The PATH_NAME column contains the absolute path name


for the object.

Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

Database performance and query optimization 753


Table 178. AUDIT_JOURNAL_PG table function (continued)

Column Name Data Type Description

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the


directory that contains the object identified in the PATH_NAME
column.
Contains the null value when PATH_NAME_INDICATOR is YES, or
if the file ID is not available or the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) CCSID 1200 The name of the object.


Contains the null value if the object name is not available or
the object is not in the "root" (/), QOpenSys, or user-defined file
systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the object is
not in the "root" (/), QOpenSys, or user-defined file systems.

OFFICE_USER VARCHAR(10) The name of the office user.


Contains the null value if there is no office user.

OFFICE_ON_BEHALF_OF_USER VARCHAR(10) User working on behalf of another user.


Contains the null value if there is no user name.

DLO_NAME VARCHAR(12) The name of the folder or document.


Contains the null value if there is no new folder or document.

FOLDER_PATH VARCHAR(63) The path of the folder.


Contains the null value if there is no new folder path.

AUTHORIZATION_LIST_MANAGEMENT VARCHAR(3) Indicates whether the new primary group has authorization list
management (*AUTLMGT) authority.

NO The new primary group does not have this authority.

YES The new primary group has this authority.

OBJECT_EXCLUDE VARCHAR(3) Indicates whether the new primary group has exclude (*EXCLUDE)
authority.

NO The new primary group does not have this authority.

YES The new primary group has this authority.

OBJECT_OPERATIONAL VARCHAR(3) Indicates whether the new primary group has object operational
(*OBJOPR) authority.

NO The new primary group does not have this authority.

YES The new primary group has this authority.

OBJECT_MANAGEMENT VARCHAR(3) Indicates whether the new primary group has object management
(*OBJMGT) authority.

NO The new primary group does not have this authority.

YES The new primary group has this authority.

OBJECT_EXISTENCE VARCHAR(3) Indicates whether the new primary group has object existence
(*OBJEXIST) authority.

NO The new primary group does not have this authority.

YES The authority might have changed.

OBJECT_ALTER VARCHAR(3) Indicates whether the new primary group has object alter
(*OBJALTER) authority.

NO The new primary group does not have this authority.

YES The new primary group has this authority.

754 IBM i: Performance and Query Optimization


Table 178. AUDIT_JOURNAL_PG table function (continued)

Column Name Data Type Description

OBJECT_REFERENCE VARCHAR(3) Indicates whether the new primary group has object reference
(*OBJREF) authority.

NO The new primary group does not have this authority.

YES The new primary group has this authority.

DATA_READ VARCHAR(3) Indicates whether the new primary group has data read (*READ)
authority.

NO The new primary group does not have this authority.

YES The new primary group has this authority.

DATA_ADD VARCHAR(3) Indicates whether the new primary group has data add (*ADD)
authority.

NO The new primary group does not have this authority.

YES The new primary group has this authority.

DATA_UPDATE VARCHAR(3) Indicates whether the new primary group has data update (*UPD)
authority.

NO The new primary group does not have this authority.

YES The new primary group has this authority.

DATA_DELETE VARCHAR(3) Indicates whether the new primary group has data delete (*DLT)
authority .

NO The new primary group does not have this authority.

YES The new primary group has this authority.

DATA_EXECUTE VARCHAR(3) Indicates whether the new primary group has data execute
(*EXECUTE) authority.

NO The new primary group does not have this authority.

YES The new primary group has this authority.

PREV_AUTHORIZATION_LIST_ VARCHAR(3) Indicates whether the previous primary group had authorization list
MANAGEMENT management (*AUTLMGT) authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

PREV_OBJECT_EXCLUDE VARCHAR(3) Indicates whether the previous primary group had exclude
(*EXCLUDE) authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

PREV_OBJECT_OPERATIONAL VARCHAR(3) Indicates whether the previous primary group had object
operational (*OBJOPR) authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

PREV_OBJECT_MANAGEMENT VARCHAR(3) Indicates whether the previous primary group had object
management (*OBJMGT) authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

Database performance and query optimization 755


Table 178. AUDIT_JOURNAL_PG table function (continued)

Column Name Data Type Description

PREV_OBJECT_EXISTENCE VARCHAR(3) Indicates whether the previous primary group had object existence
(*OBJEXIST) authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

PREV_OBJECT_ALTER VARCHAR(3) Indicates whether the previous primary group had object alter
(*OBJALTER) authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

PREV_OBJECT_REFERENCE VARCHAR(3) Indicates whether the previous primary group had object reference
(*OBJREF) authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

PREV_DATA_READ VARCHAR(3) Indicates whether the previous primary group had data read
(*READ) authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

PREV_DATA_ADD VARCHAR(3) Indicates whether the previous primary group had data add (*ADD)
authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

PREV_DATA_UPDATE VARCHAR(3) Indicates whether the previous primary group had data update
(*UPD) authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

PREV_DATA_DELETE VARCHAR(3) Indicates whether the previous primary group had data delete
(*DLT) authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

PREV_DATA_EXECUTE VARCHAR(3) Indicates whether the previous primary group had data execute
(*EXECUTE) authority.

NO The previous primary group did not have this authority.

YES The previous primary group had this authority.

Contains the null value if a previous value is not available.

Example
• List the objects in APPLIB or APPLIB2 that had their primary group changed in the last month.

SELECT LIBRARY_NAME, OBJECT_NAME, OBJECT_TYPE, PRIMARY_GROUP, PREV_PRIMARY_GROUP,


REVOKE_PREV_PRIMARY_GROUP
FROM TABLE (

756 IBM i: Performance and Query Optimization


SYSTOOLS.AUDIT_JOURNAL_PG (STARTING_TIMESTAMP => CURRENT DATE - 1 MONTH)
)
WHERE LIBRARY_NAME IN ('APPLIB', 'APPLIB2')
ORDER BY 1, 3, 2;

AUDIT_JOURNAL_PS table function


The AUDIT_JOURNAL_PS table function returns rows from the audit journal that contain information from
the PS (Profile Swap) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 179. AUDIT_JOURNAL_PS table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the PS audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Profile swap during pass-through

E End work on behalf of the relationship

H Profile handle generated by the


QSYGETPH API

I All profile tokens were invalidated

M Maximum number of profile tokens


have been generated

P Profile token generated for a user

R All profile tokens for a user have been


removed

S Start work on behalf of the relationship

T Exit program profile swap


for the Telnet exit program
QIBM_QTG_DEVINIT

U Exit program profile override


for the Telnet exit program
QIBM_QTG_DEVINIT or for
the FTP exit program
QIBM_QTMF_SVR_LOGON

V User profile authenticated

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the


entry type.

USER_PROFILE_NAME VARCHAR(10) The name of the user profile.


Contains the null value if ENTRY_TYPE is T or
U.

PROFILE_TOKEN_TYPE VARCHAR(12) The type of profile token that was generated.

MULTIPLE USE Multiple-use profile


token

REGENERATED Multiple-use
regenerated profile
token

SINGLE USE Single-use profile token

Contains the null value if no profile token


was generated.

Database performance and query optimization 757


Table 179. AUDIT_JOURNAL_PS table function (continued)

Column Name Data Type Description

PROFILE_TOKEN_TIMEOUT INTEGER The number of seconds that the profile token


is valid.
Contains the null value if no profile token
was generated.

SOURCE_LOCATION VARCHAR(8) Pass-through source location.


Contains the null value if this entry is not for
pass-through.

PASS_THROUGH_USER_PROFILE_NAME VARCHAR(10) The name of the user profile used for pass-
through.
Contains the null value if ENTRY_TYPE is T or
the name is not available.

ORIGINAL_PASS_THROUGH_USER_PROFILE_NAME VARCHAR(10) The original name of the user profile used for
pass-through.
Contains the null value if ENTRY_TYPE is T or
the name is not available.

EXIT_PROGRAM_USER_PROFILE_NAME VARCHAR(10) When ENTRY_TYPE is T, contains the name


of the user profile returned by the exit
program.
When ENTRY_TYPE is U, contains the name
of the user profile used by the exit program.
Contains the null value if ENTRY_TYPE is not
T or U or the name is not available.

NEGOTIATED_USER_PROFILE_NAME VARCHAR(10) The name of the user profile negotiated by


the Telnet client.
Contains the null value if ENTRY_TYPE is not
T or if no user was negotiated.

PORT_NUMBER INTEGER The port number of the Telnet or FTP client.


Contains the null value if ENTRY_TYPE is not
T or U or the port number is not available.

IP_ADDRESS VARCHAR(45) The IP address of the Telnet or FTP client.


Contains the null value if ENTRY_TYPE is not
T or U or the IP address is not available.

DEVICE_NAME VARCHAR(10) The name of the device that was requested


or set by the exit point.
Contains the null value if ENTRY_TYPE is not
T or U, or if no device was negotiated, or if
FTP is used.

EXIT_POINT_NAME VARCHAR(30) The name of the exit point for which the exit
program profile is overridden.
Contains the null value if ENTRY_TYPE is not
T or U or the exit point name is not available.

EXIT_POINT_FORMAT VARCHAR(8) The exit point format.


Contains the null value if ENTRY_TYPE is
not T or U or the exit point format is not
available.

OFFICE_USER VARCHAR(10) The name of the office user.


Contains the null value if there is no office
user.

OFFICE_ON_BEHALF_OF_USER VARCHAR(10) User working on behalf of the office user.


Contains the null value if the user name is
not available.

Example
• List the occurrences where a single user profile token was generated for the user QSYS in the last week.

758 IBM i: Performance and Query Optimization


SELECT * FROM TABLE(
SYSTOOLS.AUDIT_JOURNAL_PS(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS
)
)
WHERE PROFILE_TOKEN_TYPE = 'SINGLE USE' AND USER_PROFILE_NAME = 'QSECOFR';

AUDIT_JOURNAL_PU table function


The AUDIT_JOURNAL_PU table function returns rows from the audit journal that contain information from
the PU (PTF Object Change) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 180. AUDIT_JOURNAL_PU table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the PU audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

D Directory PTF object

L Library PTF object

S LIC PTF object

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

ENTRY_ACTION VARCHAR(7) The type of action.

CHANGED Changed PTF object

NEW New PTF object

PTF_OPERATION VARCHAR(6) The PTF operation.

APPLY The PTF is applied

REMOVE The PTF is removed

PRODUCT_ID VARCHAR(7) Product ID.

PRODUCT_RELEASE_LEVEL CHAR(6) Product version, release, modification in format VvRrMm.

PTF_IDENTIFIER VARCHAR(7) PTF identifier.

PRODUCT_OPTION VARCHAR(4) Product option.

LOAD_ID VARCHAR(4) Product load identifier.

PRODUCT_MINIMUM_LEVEL VARCHAR(2) Product minimum level.

PRODUCT_MAXIMUM_LEVEL VARCHAR(2) Product maximum level.

PRODUCT_LIBRARY VARCHAR(10) Product library.

OBJECT_LIBRARY VARCHAR(10) Object library.


Contains the null value if ENTRY_TYPE is not L.

OBJECT_NAME VARCHAR(10) Object name.


Contains the null value if ENTRY_TYPE is not L.

OBJECT_TYPE VARCHAR(7) Object type.


Contains the null value if ENTRY_TYPE is not L.

Database performance and query optimization 759


Table 180. AUDIT_JOURNAL_PU table function (continued)

Column Name Data Type Description

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object
resides. A value of *SYSBAS indicates the system ASP and all basic
user ASPs.
Contains the null value if ENTRY_TYPE is not D or L.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.


Contains the null value if ENTRY_TYPE is not D or L.

LIC_RU_NAME VARCHAR(8) The Licensed Internal Code replacement unit (Ru) name.
Contains the null value if ENTRY_TYPE is not S.

PATH_NAME VARGRAPHIC(5000) CCSID 1200 The path name of the object.


Contains the null value if ENTRY_TYPE is not D or the object is not in
the "root" (/), QOpenSys, or user-defined file systems.

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path


name for the object, instead it contains a relative path
name. The RELATIVE_DIRECTORY_FILE_ID can be used to
form an absolute path name with this relative path name.

YES The PATH_NAME column contains complete absolute path


name for the object.

Contains the null value if ENTRY_TYPE is not D or the object is not in


the "root" (/), QOpenSys, or user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the


directory that contains the object identified in the PATH_NAME
column.
Contains the null value if ENTRY_TYPE is not D, when
PATH_NAME_INDICATOR is YES, or if the object is not in the "root"
(/), QOpenSys, or user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) CCSID 1200 The name of the object.


Contains the null value if ENTRY_TYPE is not D or the object is not in
the "root" (/), QOpenSys, or user-defined file systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if ENTRY_TYPE is not D, or the object is not
in the "root" (/), QOpenSys, or user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if ENTRY_TYPE is not D or the object is not in
the "root" (/), QOpenSys, or user-defined file systems.

Example
• List objects that were affected by PTFs that were applied to the system in the previous two days.

SELECT PTF_IDENTIFIER, OBJECT_LIBRARY, OBJECT_NAME, OBJECT_TYPE


FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_PU (STARTING_TIMESTAMP => CURRENT DATE - 2 DAYS)
)
WHERE ENTRY_TYPE = 'L' AND PTF_OPERATION = 'APPLY';

AUDIT_JOURNAL_PW table function


The AUDIT_JOURNAL_PW table function returns rows from the audit journal that contain information
from the PW (Password) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.

760 IBM i: Performance and Query Optimization


Table 181. AUDIT_JOURNAL_PW table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the PW audit journal entry.

VIOLATION_TYPE CHAR(1) The type of violation.

A APPC bind failure.

C User authentication with the CHKPWD command failed.

D Service tools user ID name not valid (QSYCHGDS API, CRTSSTUSR,


CHGSSTUSR, DLTSSTUSR commands).

E Service tools user ID password not valid (QSYCHGDS API, CRTSSTUSR,


CHGSSTUSR, DLTSSTUSR commands).

P Password not valid.

Q Attempted signon (user authentication) failed because user profile is


disabled.

R Attempted signon (user authentication) failed because password was


expired.

S SQL Decryption password is not valid.

U User name not valid.

X Service tools user ID is disabled.

Y Service tools user ID not valid (service tools interface).

Z Service tools user ID password not valid (service tools interface).

VIOLATION_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the violation type.

AUDIT_USER_NAME VARCHAR(10) The job user name or the service tools user ID name.
Contains the null value if no user name is available.

DEVICE_NAME VARCHAR(40) The name of the device or communications device on which the password or
user ID was entered.
Contains the null value when VIOLATION_TYPE is D, E, X, Y, or Z or if the
device name is not available.

INTERFACE_NAME VARCHAR(40) The name of the interface being used.


Contains the null value when VIOLATION_TYPE is not D, E, X, Y, or Z or if the
interface name is not available.

REMOTE_LOCATION VARCHAR(8) Name of the remote location for the APPC bind.
Contains the null value when VIOLATION_TYPE is not A.

LOCAL_LOCATION VARCHAR(8) Name of the local location for the APPC bind.
Contains the null value when VIOLATION_TYPE is not A.

NETWORK_ID VARCHAR(8) Network ID for the APPC bind.


Contains the null value when VIOLATION_TYPE is not A.

DECRYPT_HOST_VARIABLE VARCHAR(3) Whether the user attempted to decrypt data in a host variable.

NO The user did not attempt to decrypt data in a host variable.

YES The user attempted to decrypt data in a host variable.

Contains the null value if VIOLATION_TYPE is not S.

DECRYPT_OBJECT_LIBRARY VARCHAR(10) The library that contains OBJECT_NAME.


Contains the null value if VIOLATION_TYPE is not S or if there is no library
name.

DECRYPT_OBJECT_NAME VARCHAR(10) The name of the object being decrypted.


Contains the null value if VIOLATION_TYPE is not S or if there is no object
name.

DECRYPT_OBJECT_TYPE VARCHAR(8) The type of the object.


Contains the null value if VIOLATION_TYPE is not S or if there is no object.

Database performance and query optimization 761


Table 181. AUDIT_JOURNAL_PW table function (continued)

Column Name Data Type Description

DECRYPT_OBJECT_ASP_NAME VARCHAR(10) The name of the ASP device where OBJECT_NAME resides.
Contains the null value if VIOLATION_TYPE is not S or if there is no object
name.

DECRYPT_OBJECT_ASP_NUMBER INTEGER The number of the ASP device where OBJECT_NAME resides.
Contains the null value if VIOLATION_TYPE is not S or if there is no object
name.

Example
• For all the password audit journal entries from yesterday and today, list the number of each type of audit
violation.

SELECT VIOLATION_TYPE CONCAT ' - ' CONCAT VIOLATION_TYPE_DETAIL,


COUNT(*) AS VIOLATION_COUNT
FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_PW ( )
)
GROUP BY VIOLATION_TYPE CONCAT ' - ' CONCAT VIOLATION_TYPE_DETAIL
ORDER BY 2 DESC;

AUDIT_JOURNAL_RA table function


The AUDIT_JOURNAL_RA table function returns rows from the audit journal that contain information from
the RA (Authority Change for Restored Object) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 182. AUDIT_JOURNAL_RA table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the RA audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Changes to authority for a restored object

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

OBJECT_LIBRARY VARCHAR(10) The name of the library containing the restored object.
Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) The name of the restored object.


Contains the null value if there is no restored object name.

OBJECT_TYPE VARCHAR(7) The type of the restored object.


Contains the null value if there is no restored object type.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which OBJECT_NAME
resides. A value of *SYSBAS indicates the system ASP and all basic user
ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the auxiliary storage pool to which storage for
OBJECT_NAME is allocated.

SAVE_AUTHORIZATION_LIST VARCHAR(10) The name of the authorization list for the object on the save media.
Contains the null value if there is no authorization list for the object on the
save media.

RESTORE_AUTHORIZATION_LIST VARCHAR(10) The name of the authorization list for the object after the restore has
completed.
Contains the null value if AUTHORIZATION_LIST_REMOVED is YES or there
is no authorization list for the object on the save media.

762 IBM i: Performance and Query Optimization


Table 182. AUDIT_JOURNAL_RA table function (continued)

Column Name Data Type Description

AUTHORIZATION_LIST_REMOVED VARCHAR(3) Indicates whether the authorization list was removed from the object.

NO The authorization list was not removed.

YES The authorization list was removed.

PUBLIC_AUTHORITY_EXCLUDE VARCHAR(3) Indicates whether public authority was set to exclude (*EXCLUDE) for the
object.

NO Public authority was not set to exclude (*EXCLUDE).

YES Public authority was set to exclude (*EXCLUDE).

PRIVATE_AUTHORITY_REMOVED VARCHAR(3) Indicates whether private authority was removed from the object.

NO Private authority was not removed.

YES Private authority was removed.

PATH_NAME VARGRAPHIC(5000) The path name of the restored object.


CCSID 1200
Contains the null value if the restored object name is not available or
the restored object is not in the "root" (/), QOpenSys, or user-defined file
systems.

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path name


for the restored object, instead it contains a relative path name. The
RELATIVE_DIRECTORY_FILE_ID can be used to form an absolute
path name with this relative path name.

YES The PATH_NAME column contains complete absolute path name for
the restored object.

Contains the null value if the restored object is not in the "root" (/),
QOpenSys, or user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the directory
that contains the object identified in the PATH_NAME column.
Contains the null value when PATH_NAME_INDICATOR is YES, or if the file
ID is not available or the restored object is not in the "root" (/), QOpenSys,
or user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) The name of the restored object.


CCSID 1200
Contains the null value if the restored object name is not available or
the restored object is not in the "root" (/), QOpenSys, or user-defined file
systems.

OBJECT_FILE_ID BINARY(16) The file ID of the restored object.


Contains the null value if the restored object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the restored object is
not in the "root" (/), QOpenSys, or user-defined file systems.

DLO_NAME VARCHAR(12) The name of the document library object.


Contains the null value if there is no document library object.

FOLDER_PATH VARCHAR(63) The path of the folder.


Contains the null value if there is no folder path.

Example
• List any objects in APPLIB1 where the public authority is not set to *EXCLUDE as a result of restores
done in the last day.

SELECT OBJECT_LIBRARY, OBJECT_NAME, OBJECT_TYPE, PUBLIC_AUTHORITY_EXCLUDE FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_RA(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 1 DAY)
)

Database performance and query optimization 763


WHERE OBJECT_LIBRARY = 'APPLIB1'
AND PUBLIC_AUTHORITY_EXCLUDE = 'NO';

AUDIT_JOURNAL_RO table function


The AUDIT_JOURNAL_RO table function returns rows from the audit journal that contain information from
the RO (Ownership Change for Restored Object) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 183. AUDIT_JOURNAL_RO table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the RO audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Changes to ownership for a restored object

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

OBJECT_LIBRARY VARCHAR(10) The name of the library containing the restored object.
Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) The name of the restored object.


Contains the null value if there is no restored object name.

OBJECT_TYPE VARCHAR(7) The type of the restored object.


Contains the null value if there is no restored object type.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which OBJECT_NAME
resides. A value of *SYSBAS indicates the system ASP and all basic user
ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the auxiliary storage pool to which storage for
OBJECT_NAME is allocated.

SAVE_OWNER VARCHAR(10) The owner of the object on the save media.

RESTORE_OWNER VARCHAR(10) The owner of the object after the restore has completed.

PATH_NAME VARGRAPHIC(5000) The path name of the restored object.


CCSID 1200
Contains the null value if the restored object name is not available or
the restored object is not in the "root" (/), QOpenSys, or user-defined file
systems.

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path name


for the restored object, instead it contains a relative path name. The
RELATIVE_DIRECTORY_FILE_ID can be used to form an absolute
path name with this relative path name.

YES The PATH_NAME column contains complete absolute path name for
the restored object.

Contains the null value if the restored object is not in the "root" (/),
QOpenSys, or user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the directory
that contains the restored object identified in the PATH_NAME column.
Contains the null value when PATH_NAME_INDICATOR is YES, or if the file
ID is not available or the restored object is not in the "root" (/), QOpenSys,
or user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) The name of the restored object.


CCSID 1200
Contains the null value if the restored object name is not available or
the restored object is not in the "root" (/), QOpenSys, or user-defined file
systems.

764 IBM i: Performance and Query Optimization


Table 183. AUDIT_JOURNAL_RO table function (continued)

Column Name Data Type Description

OBJECT_FILE_ID BINARY(16) The file ID of the restored object.


Contains the null value if the restored object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the restored object is
not in the "root" (/), QOpenSys, or user-defined file systems.

DLO_NAME VARCHAR(12) The name of the document library object.


Contains the null value if there is no document library object.

FOLDER_PATH VARCHAR(63) The path of the folder.


Contains the null value if there is no folder path.

Example
• List any objects in APPLIB1 that are owned by QSYS as a result of restores done in the last day.

SELECT OBJECT_NAME, RESTORE_OWNER FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_RO(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 1 DAY)
)
WHERE OBJECT_LIBRARY = 'APPLIB1' AND
RESTORE_OWNER = 'QSYS';

AUDIT_JOURNAL_RZ table function


The AUDIT_JOURNAL_RZ table function returns rows from the audit journal that contain information from
the RZ (Primary Group Change for Restored Object) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 184. AUDIT_JOURNAL_RZ table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the RZ audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Changes to the primary group for a restored object

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

OBJECT_LIBRARY VARCHAR(10) The name of the library containing the restored object.
Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) The name of the restored object.


Contains the null value if there is no restored object name.

OBJECT_TYPE VARCHAR(7) The type of the restored object.


Contains the null value if there is no restored object type.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which OBJECT_NAME
resides. A value of *SYSBAS indicates the system ASP and all basic user
ASPs.

OBJECT_ASP_NUMBER INTEGER The number of the auxiliary storage pool to which storage for
OBJECT_NAME is allocated.

SAVE_PRIMARY_GROUP VARCHAR(10) The primary group for the object on the save media.
Contains the null value if there is no primary group for the object on the save
media.

Database performance and query optimization 765


Table 184. AUDIT_JOURNAL_RZ table function (continued)

Column Name Data Type Description

RESTORE_PRIMARY_GROUP VARCHAR(10) The primary group for the object after the restore has completed.
Contains the null value if there is no primary group for the object on the save
media.

PATH_NAME VARGRAPHIC(5000) The path name of the restored object.


CCSID 1200
Contains the null value if the restored object name is not available or the
object is not in the "root" (/), QOpenSys, or user-defined file systems.

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator.

NO The PATH_NAME column does not contain an absolute path name


for the restored object, instead it contains a relative path name. The
RELATIVE_DIRECTORY_FILE_ID can be used to form an absolute
path name with this relative path name.

YES The PATH_NAME column contains complete absolute path name for
the restored object.

Contains the null value if the restored object is not in the "root" (/),
QOpenSys, or user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the directory
that contains the restored object identified in the PATH_NAME column.
Contains the null value when PATH_NAME_INDICATOR is YES, or if the file
ID is not available or the restored object is not in the "root" (/), QOpenSys,
or user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) The name of the restored object.


CCSID 1200
Contains the null value if the restored object name is not available or
the restored object is not in the "root" (/), QOpenSys, or user-defined file
systems.

OBJECT_FILE_ID BINARY(16) The file ID of the restored object.


Contains the null value if the restored object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the restored object is
not in the "root" (/), QOpenSys, or user-defined file systems.

DLO_NAME VARCHAR(12) The name of the document library object.


Contains the null value if there is no document library object.

FOLDER_PATH VARCHAR(63) The path of the folder.


Contains the null value if there is no folder path.

Example
• List any objects in APPLIB1 that have the primary group DEVS as a result of restores done in the last
day.

SELECT OBJECT_NAME, RESTORE_PRIMARY_GROUP FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_RZ(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 1 DAY)
)
WHERE OBJECT_LIBRARY = 'APPLIB1' AND
RESTORE_PRIMARY_GROUP = 'DEVS';

AUDIT_JOURNAL_SK table function


The AUDIT_JOURNAL_SK table function returns rows from the audit journal that contain information from
the SK (Sockets Connections) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.

766 IBM i: Performance and Query Optimization


Table 185. AUDIT_JOURNAL_SK table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the SK audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Accept

C Connect

D DHCP address assigned

F Filtered mail

I Inbound UDP traffic

O Outbound UDP traffic

P Port unavailable

R Reject mail

S Successful secure connection.


This means a secure protocol was used, not that the
algorithms used are considered secure. A system operator
needs to review SECURE_VERSION and SECURE_PROPERTIES
to determine the level of security.

U DHCP address not assigned

X Failed system TLS connection

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

ADDRESS_SPACE_TYPE CHAR(4) The address family.

IPV4 Internet Protocol Version 4

IPV6 Internet Protocol Version 6

Contains the null value when information is not available.

LOCAL_IP_ADDRESS VARCHAR(45) The local IP address.


Contains the null value when information is not available.

LOCAL_PORT INTEGER The local port.


Contains the null value when information is not available.

SOCKET_DESCRIPTOR INTEGER The socket descriptor.


Contains the null value when ENTRY_TYPE is not A, C, R, S, U or X, or
if information is not available.

MAC_ADDRESS VARCHAR(32) The MAC address of the requesting client.


Contains the null value when information is not available.

HOST_NAME VARCHAR(255) The host name of the requesting client.


Contains the null value when information is not available.

DHCP_IP_ADDRESS VARCHAR(45) The IP address that the DHCP server assigned to the requesting
client.
Contains the null value when ENTRY_TYPE is not D.

SECURE_VERSION VARCHAR(10) The security protocol including the specific version level, if available,
used for the connection. Protocol prefixes include: TLS, DTLS, SSL,
IKE, IPSEC, SSH.
A specific example would be 'TLSV1.2' if the connection is protected
by System TLS using TLSv1.2. An entry for a non-operating system
connection may contain a raw version value such as '0401' if the
system inspection code encounters a version it doesn't understand.
Contains the null value when ENTRY_TYPE is not S.

Database performance and query optimization 767


Table 185. AUDIT_JOURNAL_SK table function (continued)

Column Name Data Type Description

SECURE_PROPERTIES VARCHAR(100) The secure properties used for the connection.


The content of this column varies based on SECURE_VERSION.
Where possible this field contains one or more blank-separated
character strings describing the cryptographic algorithms and key
sizes used for the connection. The algorithms and key sizes are
presented in a character format associated with the secure version
field. A TLSv1.2 entry may look like this:
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_ SHA384
ECDSA_SHA512 SECP521R1
An entry for a non-operating system connection may contain
a protocol's internal algorithm representation values such as
'C054 0703 29' if the system inspection code encounters unknown
values.
Contains the null value when ENTRY_TYPE is not S.

SECURE_INFORMATION VARCHAR(100) Additional attributes for the secure connection. For example, for
IPSEC connections it contains the VPN Connection Name.
Contains the null value when ENTRY_TYPE is not S or when
information is not available.

TLS_ERROR_CODE VARCHAR(100) A string that represents the TLS error code.


Contains the null value when ENTRY_TYPE is not X.

TLS_ERROR_DESCRIPTION VARCHAR(100) A string that describes the TLS failure.


Contains the null value when ENTRY_TYPE is not X.

FILTER_DESCRIPTION VARCHAR(10) The specified mail filter.


Contains the null value when ENTRY_TYPE is not F.

FILTER_DATA VARCHAR(512) The mail filter data.


Contains the null value when ENTRY_TYPE is not F.

Example
• List the security protocols and cryptographic algorithms used in the last month.

SELECT DISTINCT SECURE_VERSION, SECURE_PROPERTIES FROM TABLE(


SYSTOOLS.AUDIT_JOURNAL_SK(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 1 MONTH
)
)
WHERE ENTRY_TYPE = 'S';

AUDIT_JOURNAL_SM table function


The AUDIT_JOURNAL_SM table function returns rows from the audit journal that contain information from
the SM (Systems Management Change) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 186. AUDIT_JOURNAL_SM table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the SM audit journal entry.

768 IBM i: Performance and Query Optimization


Table 186. AUDIT_JOURNAL_SM table function (continued)

Column Name Data Type Description

ENTRY_TYPE CHAR(1) The type of entry.

B Backup list changed

C Automatic cleanup options

D DRDA

F HFS file system

M Change DDM TCP/IP Attributes (CHGDDMTCPA) CL command

N Network file operation

O Backup options changed

P Power on/off schedule

S System reply list

T Access path recovery times changed

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

ACCESS_TYPE VARCHAR(8) The type of access.

ADD Add

CHANGE Change

DELETE Delete

DISPLAY Display

REMOVE Remove

RETRIEVE Retrieve or receive

Contains the null value when information is not available.

REPLY_SEQUENCE_NUMBER INTEGER Sequence number of the action.


Contains the null value if ENTRY_TYPE is not S or if ACCESS_TYPE is
DISPLAY.

REPLY_MESSAGE_ID VARCHAR(7) Message ID associated with the action. Can contain the special
value *ANY.
Contains the null value if ENTRY_TYPE is not S.

FILE_SYSTEM_NAME VARCHAR(10) Name of the file system.


Contains the null value if ENTRY_TYPE is not F.

BACKUP_OPTION VARCHAR(8) The backup option that was changed. Values are *DAILY, *WEEKLY,
and *MONTHLY.
Contains the null value if ENTRY_TYPE is not O.

BACKUP_LIST VARCHAR(4) The name of the backup list that was changed. Values are *FLD and
*LIB.
Contains the null value if ENTRY_TYPE is not B.

NETWORK_FILE VARCHAR(10) The name of the network file that was used.
Contains the null value if ENTRY_TYPE is not N.

NETWORK_FILE_MEMBER VARCHAR(10) The name of the member of the network file.


Contains the null value if ENTRY_TYPE is not N or if the information
is not available.

NETWORK_FILE_NUMBER INTEGER The number of the network file.


Contains the null value if ENTRY_TYPE is not N.

NETWORK_FILE_OWNER VARCHAR(10) The name of the user profile that owns the network file.
Contains the null value if ENTRY_TYPE is not N.

NETWORK_FILE_ORIGINATOR VARCHAR(8) The name of the user profile that originated the network file.
Contains the null value if ENTRY_TYPE is not N.

Database performance and query optimization 769


Table 186. AUDIT_JOURNAL_SM table function (continued)

Column Name Data Type Description

NETWORK_FILE_ADDRESS VARCHAR(8) The address that originated the network file.


Contains the null value if ENTRY_TYPE is not N.

RDB_NAME VARCHAR(18) Name of the relational database.


When ENTRY_TYPE is D, can contain the following special values:

*ALL All entries in the RDB directory were removed.

*ALLRMT All entries except the *LOCAL entry in the RDB


directory were removed.

Contains the null value if ENTRY_TYPE is not D or M.

RDB_ALIAS VARCHAR(18) The RDB alias name. This value may be *NONE.
Contains the null value if ENTRY_TYPE is not D.

REMOTE_LOCATION_TYPE VARCHAR(4) The remote location type.

*IP The RDB is found using a host name or an internet address


over a TCP/IP connection.

*SNA The RDB is accessed using a Systems Network


Architecture (SNA) address and protocol.

Contains the null value if ENTRY_TYPE is not D or if the information


is not available.

REMOTE_LOCATION VARCHAR(254) The remote location name of the system on which the RDB is
located.

remote- The remote location name is in one of the


location-name following formats:
• SNA remote location name (LU name).
• SNA remote network identifier and remote
location name separated by a period.
• IPv4 address in dotted decimal form.
• IPv6 address in colon hexadecimal form.
• IP host domain name.

*ARDPGM The RDB is accessed by using the Application


Requester Driver (ARD) program.

*LOCAL The system database on this system.

*LOOPBACK This value is an alias for the IP address of the


host system.

*MIRROR The RDB is accessed on the other system for a


Db2 Mirror relationship.

Contains the null value if ENTRY_TYPE is not D or if the information


is not available.

REMOTE_PORT_OR_SERVICE VARCHAR(14) The relational database entry port number or service name that is
used at the remote location to communicate with the system on
which the RDB is located. If *DRDA was specified, the Distributed
Relational Database Architecture (DRDA) port 446 is shown.
Contains the null value if ENTRY_TYPE is not D,
REMOTE_LOCATION_TYPE is not *IP, or if the information is not
available.

PREFERRED_AUTHENTICATION VARCHAR(10) The preferred authentication method on a connection request.

*ENCRYPTED User ID and encrypted password.

*ENCUSRPWD Encrypted user ID and encrypted password.

*KERBEROS Authentication occurs using Kerberos.

*USRENCPWD User ID and encrypted password

*USRID User ID only.

*USRIDPWD User ID and password.

Contains the null value if ENTRY_TYPE is not D or if the information


is not available.

770 IBM i: Performance and Query Optimization


Table 186. AUDIT_JOURNAL_SM table function (continued)

Column Name Data Type Description

LOWER_AUTHENTICATION VARCHAR(11) Whether an authentication method lower than what was specified
for the preferred method will be accepted during negotiation with
the server.

*ALWLOWER Allow negotiation of a lower authentication


method.

*NOALWLOWER Do not allow negotiation of a lower


authentication method.

Contains the null value if ENTRY_TYPE is not D or if the information


is not available.

ENCRYPTION_ALGORITHM VARCHAR(4) The encryption algorithm to be used initially on the connection


request.

*AES Advanced Encryption Standard (AES) is to be used initially.

*DES Data Encryption Standard (DES) is to be used initially.

Contains the null value if ENTRY_TYPE is not D,


REMOTE_LOCATION_TYPE is not *IP, or if the information is not
available.

SECURE_CONNECTION VARCHAR(5) Whether Transport Layer Security (TLS) is to be used on a DDM/


DRDA TCP/IP connection request.

*NONE TLS is not used.

*SSL TLS is used.

*TLS TLS is used.

Contains the null value if ENTRY_TYPE is not D,


REMOTE_LOCATION_TYPE is not *IP, or if the information is not
available.

APPC_DEVICE_DESCRIPTION VARCHAR(10) The Advanced Program-to-Program Communications (APPC) device


description on this system that is used with this RDB entry. Can
contain the special value:

*LOC If APPC is being used, the system determines which device


description is used.

Contains the null value if ENTRY_TYPE is not D,


REMOTE_LOCATION_TYPE is not *SNA, or if the information is not
available.

LOCAL_LOCATION VARCHAR(8) The local location name by which this system is identified to the
system on which the RDB is located. Can contain one of the
following special values:

*LOC If APPC is being used, the system determines which


local location name is used.

*NETATR The LCLLOCNAME value specified in the system


network attributes is used.

Contains the null value if ENTRY_TYPE is not D,


REMOTE_LOCATION_TYPE is not *SNA, or if the information is not
available.

REMOTE_NETWORK_ID VARCHAR(8) The remote network identifier of the system on which the RDB is
located. Can contain one of the following special values:

*LOC If APPC is being used, the system determines which


remote network identifier is used.

*NETATR The remote network identifier specified in the network


attributes is used.

*NONE No remote network identifier is used.

Contains the null value if ENTRY_TYPE is not D,


REMOTE_LOCATION_TYPE is not *SNA, or if the information is not
available.

Database performance and query optimization 771


Table 186. AUDIT_JOURNAL_SM table function (continued)

Column Name Data Type Description

REMOTE_MODE VARCHAR(8) The mode name to use with the remote location name to
communicate with the system on which the RDB is located. Can
contain one of the following special values:

*NETATR The mode in the network attributes is used.

BLANK A mode name of all blanks is used.

Contains the null value if ENTRY_TYPE is not D,


REMOTE_LOCATION_TYPE is not *SNA, or if the information is not
available.

TRANSACTION_PROGRAM VARCHAR(8) FOR BIT DATA The name of the transaction program to use with the RDB entry.

transaction- The transaction program name is in one of the


program-name following formats:
• A 4-byte hexadecimal name. For example,
X'07F6C4C2'.
• An 8-byte character name.
• If *DRDA was specified, the Distributed
Relational Database Architecture (DRDA)
transaction program name, X'07F6C4C2'.

Contains the null value if ENTRY_TYPE is not D,


REMOTE_LOCATION_TYPE is not *SNA, or if the information is not
available.

ARD_LIBRARY VARCHAR(10) The library containing the Application Requester Driver (ARD)
program. This value can be *LIBL or *CURLIB.
Contains the null value if the special value *DRDA was specified on
the command, if ENTRY_TYPE is not D, if REMOTE_LOCATION is not
*ARDPGM, or if the information is not available.

ARD_PROGRAM VARCHAR(10) The ARD program to be called to process SQL requests directed to
the RDB.
Contains the null value if the special value *DRDA was specified on
the command, if ENTRY_TYPE is not D, if REMOTE_LOCATION is not
*ARDPGM, or if the information is not available.

PREV_REMOTE_LOCATION_TYPE VARCHAR(4) The previous value for the remote location type.
Contains the null value if ENTRY_TYPE is not D or if the previous
value is not available.

PREV_REMOTE_LOCATION VARCHAR(254) The previous value for the remote location name of the system on
which the RDB is located.
Contains the null value if ENTRY_TYPE is not D or if the previous
value is not available.

PREV_REMOTE_PORT_OR_SERVICE VARCHAR(14) The previous value for the relational database entry port number or
service name that is used at the remote location to communicate
with the system on which the RDB is located.
Contains the null value if ENTRY_TYPE is not D, if
REMOTE_LOCATION_TYPE is not *IP, or if the previous value is not
available.

PREV_PREFERRED_AUTHENTICATION VARCHAR(10) The previous value for the preferred authentication method on a
connection request.
Contains the null value if ENTRY_TYPE is not D or if the previous
value is not available.

PREV_LOWER_AUTHENTICATION VARCHAR(11) The previous value for whether an authentication method lower than
what was specified for the preferred method will be accepted during
negotiation with the server.
Contains the null value if ENTRY_TYPE is not D or if the previous
value is not available.

PREV_ENCRYPTION_ALGORITHM VARCHAR(4) The previous value for the encryption algorithm to be used initially
on the connection request.
Contains the null value if ENTRY_TYPE is not D, if
REMOTE_LOCATION_TYPE is not *IP, or if the previous value is not
available.

772 IBM i: Performance and Query Optimization


Table 186. AUDIT_JOURNAL_SM table function (continued)

Column Name Data Type Description

PREV_SECURE_CONNECTION VARCHAR(5) The previous value for whether Transport Layer Security (TLS) is to
be used on a DDM/DRDA TCP/IP connection request.
Contains the null value if ENTRY_TYPE is not D, if
REMOTE_LOCATION_TYPE is not *IP, or if the previous value is not
available.

PREV_APPC_DEVICE_DESCRIPTION VARCHAR(10) The previous value for the Advanced Program-to-Program


Communications (APPC) device description on this system that is
used with this RDB entry.
Contains the null value if ENTRY_TYPE is not D, if the previous value
is not available, or REMOTE_LOCATION_TYPE is not *SNA.

PREV_LOCAL_LOCATION VARCHAR(8) The previous value for the local location name by which this system
is identified to the system on which the RDB is located.
Contains the null value if ENTRY_TYPE is not D, if the previous value
is not available, or REMOTE_LOCATION_TYPE is not *SNA.

PREV_REMOTE_NETWORK_ID VARCHAR(8) The previous value for the remote network identifier of the system
on which the RDB is located.
Contains the null value if ENTRY_TYPE is not D, if the previous value
is not available, or REMOTE_LOCATION_TYPE is not *SNA.

PREV_REMOTE_MODE VARCHAR(8) The previous value for the mode name to use with the remote
location name to communicate with the system on which the RDB is
located. Can contain one of the following special values:
Contains the null value if ENTRY_TYPE is not D, if the previous value
is not available, or REMOTE_LOCATION_TYPE is not *SNA.

PREV_TRANSACTION_PROGRAM VARCHAR(8) FOR BIT DATA The previous value for the name of the transaction program to use
with the RDB entry.
Contains the null value if ENTRY_TYPE is not D, if the previous value
is not available, or REMOTE_LOCATION_TYPE is not *SNA.

PREV_ARD_LIBRARY VARCHAR(10) The previous value for the library containing the Application
Requester Driver (ARD) program. This value may be *LIBL or
*CURLIB.
Contains the null value if ENTRY_TYPE is not D, if
REMOTE_LOCATION is not *ARDPGM, or if the previous value is not
available.

PREV_ARD_PROGRAM VARCHAR(10) The previous value for the ARD program to be called to process SQL
requests directed to the RDB.
Contains the null value if ENTRY_TYPE is not D, if
REMOTE_LOCATION is not *ARDPGM, or if the previous value is not
available.

AUTOSTART_SERVER VARCHAR(4) Whether the DDM server is automatically started. This value was
set using the Change DDM TCP/IP Attributes (CHGDDMTCPA) CL
command.

*NO Do not automatically start the DDM server.

*YES Automatically start the DDM server.

Contains the null value if ENTRY_TYPE is not M or if the information


is not available.

Database performance and query optimization 773


Table 186. AUDIT_JOURNAL_SM table function (continued)

Column Name Data Type Description

LOWEST_AUTHENTICATION_METHOD VARCHAR(10) The lowest level of password security required. This value was
set using the Change DDM TCP/IP Attributes (CHGDDMTCPA) CL
command.

*ENCRYPTED User ID and encrypted password. Same as


*USRENCPWD.

*ENCUSRPWD Encrypted user ID and encrypted password.

*KERBEROS Authentication occurs using Kerberos.

*NO User ID only. Same as *USRID.

*USRID User ID only.

*USRENCPWD User ID and encrypted password

*USRIDPWD User ID and password.

*VLDONLY User ID only but if a password is sent on the


request, it must be valid.

*YES User ID and password. Same as*USRIDPWD.

Contains the null value if ENTRY_TYPE is not M or D with


an ACCESS_TYPE of ADD, CHANGE, REMOVE, or RETRIEVE,
ENTRY_TYPE is D and REMOTE_LOCATION is not *LOCAL, or if the
information is not available.

LOWEST_ENCRYPTION_ALGORITHM VARCHAR(4) The lowest encryption algorithm allowed on an incoming connection


request. This value was set using the Change DDM TCP/IP Attributes
(CHGDDMTCPA) CL command.

*AES Advanced Encryption Standard (AES) allowed.

*DES Data Encryption Standard (DES) or higher encryption


algorithm allowed.

Contains the null value if ENTRY_TYPE is not M or D with


an ACCESS_TYPE of ADD, CHANGE, REMOVE, or RETRIEVE,
ENTRY_TYPE is D and REMOTE_LOCATION is not *LOCAL, or if the
information is not available.

PREV_AUTOSTART_SERVER VARCHAR(4) The previous value for whether the DDM server is automatically
started.
Contains the null value if ENTRY_TYPE is not M or if the previous
value is not available.

PREV_LOWEST_AUTHENTICATION_ VARCHAR(10) The previous value for the lowest level of password security
METHOD required.
Contains the null value if ENTRY_TYPE is not M or if the previous
value is not available.

PREV_LOWEST_ENCRYPTION_ VARCHAR(4) The previous value for the lowest encryption algorithm allowed on
ALGORITHM an incoming connection request.
Contains the null value if ENTRY_TYPE is not M or if the previous
value is not available.

Example
• List the DRDA configuration changes related to authentication made this month.

SELECT RDB_NAME, PREFERRED_AUTHENTICATION, LOWER_AUTHENTICATION, ENCRYPTION_ALGORITHM,


SECURE_CONNECTION FROM TABLE(
SYSTOOLS.AUDIT_JOURNAL_SM(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 1 MONTH
)
)
WHERE ENTRY_TYPE = 'D';

774 IBM i: Performance and Query Optimization


AUDIT_JOURNAL_ST table function
The AUDIT_JOURNAL_ST table function returns rows from the audit journal that contain information from
the ST (Service Tools Action) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 187. AUDIT_JOURNAL_ST table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the ST audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Service record

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

SERVICE_TOOL CHAR(2) The service tool identifier.

AR ARM diagnostic trace (see ARMSRV QShell command)

AS Storage altered by Display/Alter/Dump service tool or by a remote


service tool debugger

CD QTACTLDV, QTADMPDV

CE QWTCTLTR

CS STRCPYSCN

CT DMPCLUTRC

DC DLTCMNTRC

DD DMPDLO

DF QWTDMPFR, QWTDMPLF

DI QSCDIRD

DM DMPMEMINF

DO DMPOBJ

DS DMPSYSOBJ, QTADMPTS, QTADMPDV, QWTDMPLF

DU DMPUSRPRF

DW STRDW, ENDDW, ADDDWDFN, RMVDWDFN

EC ENDCMNTRC

ER ENDRMTSPT

FF FFDC (First Failure Data Capture)

GS QSMGSSTD

HD QYHCHCOP (DASD)

HL QYHCHCOP (LPAR)

JW STRJW, ENDJW, ADDJWDFN, RMVJWDFN

MC QWTMAINT (change)

MD QWTMAINT (dump)

MP End system job

MQ Restart system job

OP Operations console

PC PRTCMNTRC

PE PRTERRLOG, QTADMPDV

Database performance and query optimization 775


Table 187. AUDIT_JOURNAL_ST table function (continued)

Column Name Data Type Description

SERVICE_TOOL (continued)
PI PRTINTDTA, QTADMPDV

PS QP0FPTOS

SC STRCMNTRC, QSCCHGCT

SE QWTSETTR

SF QWCCDSIC, QWVRCSTK (Display internal stack entry)

SJ STRSRVJOB

SN QPZSYNC

SR STRRMTSPT

SS QFPHPSF

ST STRSST

SV QSRSRV

TA TRCTCPAPP

TC TRCCNN (*FORMAT specified)

TE ENDTRC, ENDPEX, TRCJOB(*OFF or *END specified)

TI TRCINT, or TRCCNN with SET(*ON), SET(*OFF), or SET(*END)

TO QTOBSRV

TQ QWCTMQTM

TS STRTRC, STRPEX, TRCJOB(*ON specified)

UD QTAUPDDV

WE ENDWCH, QSCEWCH

WS STRWCH, QSCSWCH

WT WRKTRC

WW WRKWCH, QSCRWCHI, QSCRWCHL

SERVICE_TOOL_DETAIL VARCHAR(200) Descriptive text that corresponds to the service tool.

OBJECT_LIBRARY VARCHAR(10) Name of the library for OBJECT_NAME.


Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) Name of the object accessed.


Contains the null value if there is no object name.

OBJECT_TYPE VARCHAR(7) Type of object.


Contains the null value if there is no object type.

OBJECT_ASP_NAME VARCHAR(10) ASP name for object library.


Contains the null value if there is no object ASP name.

OBJECT_ASP_NUMBER INTEGER ASP number for object library.


Contains the null value if there is no object ASP number.

DLO_NAME VARCHAR(12) Name of the document library object.


Contains the null value if there is no document library object.

FOLDER_PATH VARCHAR(63) The folder containing the document library object


Contains the null value if there is no folder.

SOURCE_NODE_ID VARCHAR(8) Source node ID.


Contains the null value if there is no source node ID.

SOURCE_USER VARCHAR(10) Source user.


Contains the null value if there is no source user.

TARGET_QUALIFIED_JOB_NAME VARCHAR(28) The qualified job name of the target job.


Contains the null value if there is no target job.

776 IBM i: Performance and Query Optimization


Table 187. AUDIT_JOURNAL_ST table function (continued)

Column Name Data Type Description

TARGET_JOB_NAME VARCHAR(10) The job name of the target job.


Contains the null value if there is no target job.

TARGET_JOB_USER VARCHAR(10) The job user of the target job.


Contains the null value if there is no target job.

TARGET_JOB_NUMBER VARCHAR(6) The job number of the target job.


Contains the null value if there is no target job.

TARGET_JOB_USER_IDENTITY VARCHAR(10) The job user identity value of the target job.
Contains the null value if there is no target job.

DMPSYSOBJ_LIBRARY VARCHAR(30) Name of the library for the object for DMPSYSOBJ.
Contains the null value when SERVICE_TOOL is not DS.

DMPSYSOBJ_OBJECT VARCHAR(30) Name of the object for DMPSYSOBJ.


Contains the null value when SERVICE_TOOL is not DS.

DMPSYSOBJ_TYPE VARCHAR(7) Type of the object for DMPSYSOBJ.


Contains the null value when SERVICE_TOOL is not DS.

DMPSYSOBJ_ASP_NAME VARCHAR(10) ASP name for DMPSYSOBJ object library.


Contains the null value when SERVICE_TOOL is not DS.

DMPSYSOBJ_ASP_NUMBER INTEGER ASP number for DMPSYSOBJ object library.


Contains the null value when SERVICE_TOOL is not DS.

AA_COMMAND_NAME VARCHAR(30) Advanced Analysis Command name. See QMGTOOLS: Run AA Macros
Contains the null value when SERVICE_TOOL is not GS.

EARLY_TRACE_ACTION VARCHAR(6) The action requested for early job tracing

*OFF Early tracing turned off

*ON Early tracing turned on

*RESET Early tracing turned off and trace information deleted.

Contains the null value when SERVICE_TOOL is not CE.

ARM_TRACE VARCHAR(10) ARM diagnostic trace.

ACTIVATE Activate

DEACTIVATE Deactivate

Contains the null value when SERVICE_TOOL is not AR.

TRCTCPAPP_OPTION VARCHAR(7) The trace option specified on TRCTCPAPP.

ENDED Collection of trace information ended and all trace information


purged (no output created)

STARTED Collection of trace information started

STOPPED Collection of trace information stopped and trace information


written to spooled file

Contains the null value when SERVICE_TOOL is not TA.

APPLICATION_TRACED VARCHAR(10) The name of the application being traced.


Contains the null value when SERVICE_TOOL is not AR or TA.

SERVICE_TOOLS_PROFILE VARCHAR(10) The name of the service tools profile used for Start System Service Tools
(STRSST).
Contains the null value when SERVICE_TOOL is not ST or OP.

Database performance and query optimization 777


Table 187. AUDIT_JOURNAL_ST table function (continued)

Column Name Data Type Description

CONSOLE_TYPE VARCHAR(7) The console type.

*DIRECT

*HMC

*LAN

Contains the null value when SERVICE_TOOL is not OP.

CONSOLE_ACTION VARCHAR(9) The console action.

*RECOVERY

*TAKEOVER

Contains the null value when SERVICE_TOOL is not OP.

ADDRESS_FAMILY VARCHAR(5) The address family.

*IPV4

*IPV6

Contains the null value when SERVICE_TOOL is not OP or CONSOLE_TYPE is


not *LAN.

CURRENT_IP_ADDRESS VARCHAR(45) The IP address of the current console device for *LAN.
Contains the null value when SERVICE_TOOL is not OP or CONSOLE_TYPE is
not *LAN.

CURRENT_DEVICE_ID VARCHAR(10) The service tools device ID of the current console device for *LAN.
Contains the null value when SERVICE_TOOL is not OP or CONSOLE_TYPE is
not *LAN.

PREVIOUS_IP_ADDRESS VARCHAR(45) The IP address of the previous console device for *LAN.
Contains the null value when SERVICE_TOOL is not OP or CONSOLE_TYPE is
not *LAN or there is no previous console device.

PREVIOUS_DEVICE_ID VARCHAR(10) The service tools device ID of the previous console device for *LAN.
Contains the null value when SERVICE_TOOL is not OP or CONSOLE_TYPE is
not *LAN or there is no previous console device.

WATCH_SESSION VARCHAR(10) Watch session ID.


Contains the null value when SERVICE_TOOL is not WE or WS.

SERVICE_TOOL_USERID VARCHAR(10) Service tools user ID if storage was altered from DST or *DEBUG if storage
was altered by a remote service tool debugger.
Contains the null value when SERVICE_TOOL is not AS.

USER_PROFILE VARCHAR(10) User profile name if storage was altered from SST.
Contains the null value when SERVICE_TOOL is not AS.

LIC_RU_NAME VARCHAR(8) The Licensed Internal Code Replaceable Unit name.


Contains the null value when SERVICE_TOOL is not AS.

ADDRESS_OF_ALTERED_STORAGE BINARY(8) Address of storage that was altered.


Contains the null value when SERVICE_TOOL is not AS.

SEGMENT_TYPE BINARY(2) Type of segment that was altered.


Contains the null value when SERVICE_TOOL is not AS.

NUMBER_OF_ALTERED_BYTES INTEGER The number of bytes of storage in ALTERED_STORAGE_VALUE that were


changed.
Contains the null value when SERVICE_TOOL is not AS.

ALTERED_STORAGE_VALUE BINARY(16) Altered storage value.


Contains the null value when SERVICE_TOOL is not AS.

PREVIOUS_STORAGE_VALUE BINARY(16) Original storage value.


Contains the null value when SERVICE_TOOL is not AS.

778 IBM i: Performance and Query Optimization


Example
• Check whether anyone has changed storage using STRSST today.

SELECT *
FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_ST (STARTING_TIMESTAMP => CURRENT DATE)
)
WHERE SERVICE_TOOL = 'ST' AND NUMBER_OF_ALTERED_BYTES > 0;

AUDIT_JOURNAL_SV table function


The AUDIT_JOURNAL_SV table function returns rows from the audit journal that contain information from
the SV (Action to System Value) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 188. AUDIT_JOURNAL_SV table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the SV audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

A Change to system values

B Change to service attributes

C Change to system clock

D Adjustment to Coordinated Universal Time (UTC)

E Change to option

F Change to system-wide journal attribute

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

SYSTEM_VALUE VARCHAR(10) The name of the system value or service attribute that was changed. Can
contain one of the following special values.

CACHEWAIT Changed journal maximum cache wait time

JRNRCYCNT Changed journal recovery count value

QINPIDCO Change the current install disk configuration option with


QINPIDCO API.

OLD_VALUE VARCHAR(1500) The value of the system value or service attribute before it was changed.

NEW_VALUE VARCHAR(1500) The new value of the system value or service attribute.

Example
• List any system value changes that have been made in the current calendar year.

SELECT *
FROM TABLE (
SYSTOOLS.AUDIT_JOURNAL_SV (STARTING_TIMESTAMP => TRUNC_TIMESTAMP(CURRENT DATE, 'YEAR'))
)
WHERE ENTRY_TYPE = 'A';

Database performance and query optimization 779


AUDIT_JOURNAL_ZC table function
The AUDIT_JOURNAL_ZC table function returns rows from the audit journal that contain information from
the ZC (Change to Object) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 189. AUDIT_JOURNAL_ZC table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the ZC audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

C Change of an object

U Upgrade of open access to an object

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

ACCESS_TYPE INTEGER Type of access. See Numeric codes for access types for a list of the
codes for access types.

ACCESS_TYPE_DETAIL VARCHAR(50) Descriptive text that corresponds to ACCESS_TYPE.

LIBRARY_NAME VARCHAR(10) The name of the library.


Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) The name of the object.


Contains the null value if there is no object name.

OBJECT_TYPE VARCHAR(7) The type of object.


Contains the null value if there is no object type.

MEMBER_NAME VARCHAR(10) The member name for a *FILE object.


Contains the null value if OBJECT_TYPE is not *FILE or if there is no
member name.

PREV_MEMBER_NAME VARCHAR(10) The previous member name for a *FILE object.


Contains the null value if OBJECT_TYPE is not *FILE or if
ACCESS_TYPE is not 39 (Rename).

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object
resides. A value of *SYSBAS indicates the system ASP and all basic
user ASPs.
Contains the null value if there is no ASP information.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.


Contains the null value if there is no ASP information.

IFS_ACCESS_TYPE VARCHAR(50) IFS access type. See QP0LJRNL in QSYSINC/H for the list of values.
Contains the null value if the operation was not for an IFS object.

IFS_ACCESS_TYPE_DETAIL VARCHAR(2000) CCSID 1208 Descriptive text that corresponds to IFS_ACCESS_TYPE. The
value is returned as an array within a JSON object.
It is formatted as:{"IFS_ACCESS_LIST":["first-string",
"second-string", ...]}

PATH_NAME VARGRAPHIC(5000) CCSID 1200 The path name of the object.


Contains the null value if the path name is not available or the object
is not in the "root" (/), QOpenSys, or user-defined file systems.

780 IBM i: Performance and Query Optimization


Table 189. AUDIT_JOURNAL_ZC table function (continued)

Column Name Data Type Description

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator:

NO The PATH_NAME column does not contain an absolute path


name for the object, instead it contains a relative path name.
The RELATIVE_DIRECTORY_FILE_ID can be used to form an
absolute path name with this relative path name.

YES The PATH_NAME column contains the absolute path name


for the object.

Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the


directory that contains the object identified in the PATH_NAME
column.
Contains the null value when PATH_NAME_INDICATOR is YES, or
if the file ID is not available or the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) CCSID 1200 The name of the object.


Contains the null value if the object name is not available or
the object is not in the "root" (/), QOpenSys, or user-defined file
systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the object is
not in the "root" (/), QOpenSys, or user-defined file systems.

IMGCLGE_ACCESS_TYPE VARCHAR(10) Access type for the image catalog entry.

READ The file containing the image catalog entry is read-


only.

READ WRITE The file containing the image catalog entry is read/
write capable.

Contains the null value if the operation was against an image catalog
or the object type is not *IMGCLG.

IMGCLGE_INDEX_NUMBER INTEGER Index number of the image catalog entry.


Contains the null value if the operation was against an image catalog
or the object type is not *IMGCLG.

IMGCLGE_VOLUME_ID VARCHAR(32) Volume ID of the image catalog entry. Can contain the special value
*GEN.
Contains the null value if the operation was against an image catalog
or the object type is not *IMGCLG.

IMGCLGE_WRITE_PROTECTION VARCHAR(3) The write protection for the image catalog entry.

NO The file containing the image catalog entry is not write


protected.

YES The file containing the image catalog entry is write


protected..

Contains the null value if the operation was against an image catalog
or the object type is not *IMGCLG.

IMGCLGE_VIRTUAL_DEVICE VARCHAR(10) The name of the virtual device for the image catalog entry.
Contains the null value if the operation was against an image
catalog, the image catalog is not in Ready status, or the object type
is not *IMGCLG.

Example
• List objects in the IFS that start with the letters 'data' that were modified in the last week.

Database performance and query optimization 781


SELECT IFS_OBJECT_NAME, PATH_NAME, ACCESS_TYPE FROM TABLE(
SYSTOOLS.AUDIT_JOURNAL_ZC(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS
)
)
WHERE ENTRY_TYPE = 'C' AND
IFS_OBJECT_NAME LIKE 'data%'
ORDER BY PATH_NAME, IFS_OBJECT_NAME;

AUDIT_JOURNAL_ZR table function


The AUDIT_JOURNAL_ZR table function returns rows from the audit journal that contain information from
the ZR (Read of Object) journal entries.
Every audit journal table function shares a common authorization requirement and a common set of
parameters. These are described in “AUDIT JOURNAL table function common information” on page 658.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 190. AUDIT_JOURNAL_ZR table function

Column Name Data Type Description

The first columns returned by this table function are from the common audit journal entry header. See Common columns returned from the
audit journal entry header for the column definitions. After the common columns are the following columns that describe the entry specific
data for the ZR audit journal entry.

ENTRY_TYPE CHAR(1) The type of entry.

R Read of an object

ENTRY_TYPE_DETAIL VARCHAR(200) Descriptive text that corresponds to the entry type.

ACCESS_TYPE INTEGER Type of access. See Numeric codes for access types for a list of the
codes for access types.

ACCESS_TYPE_DETAIL VARCHAR(50) Descriptive text that corresponds to ACCESS_TYPE.

LIBRARY_NAME VARCHAR(10) The name of the library.


Contains the null value if there is no library name.

OBJECT_NAME VARCHAR(10) The name of the object.


Contains the null value if there is no object name.

OBJECT_TYPE VARCHAR(7) The type of object.


Contains the null value if there is no object type.

MEMBER_NAME VARCHAR(10) The member name for a *FILE object.


Contains the null value if OBJECT_TYPE is not *FILE or if there is no
member name.

OBJECT_ASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP) in which the object
resides. A value of *SYSBAS indicates the system ASP and all basic
user ASPs.
Contains the null value if there is no ASP information.

OBJECT_ASP_NUMBER INTEGER The number of the ASP device.


Contains the null value if there is no ASP information.

PATH_NAME VARGRAPHIC(5000) CCSID 1200 The path name of the object.


Contains the null value if the path name is not available or the object
is not in the "root" (/), QOpenSys, or user-defined file systems.

782 IBM i: Performance and Query Optimization


Table 190. AUDIT_JOURNAL_ZR table function (continued)

Column Name Data Type Description

PATH_NAME_INDICATOR VARCHAR(3) Path name indicator:

NO The PATH_NAME column does not contain an absolute path


name for the object, instead it contains a relative path name.
The RELATIVE_DIRECTORY_FILE_ID can be used to form an
absolute path name with this relative path name.

YES The PATH_NAME column contains the absolute path name


for the object.

Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) When PATH_NAME_INDICATOR is NO, contains the file ID of the


directory that contains the object identified in the PATH_NAME
column.
Contains the null value when PATH_NAME_INDICATOR is YES, or
if the file ID is not available or the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

IFS_OBJECT_NAME VARGRAPHIC(512) CCSID 1200 The name of the object.


Contains the null value if the object name is not available or
the object is not in the "root" (/), QOpenSys, or user-defined file
systems.

OBJECT_FILE_ID BINARY(16) The file ID of the object.


Contains the null value if the object is not in the "root" (/),
QOpenSys, or user-defined file systems.

PARENT_FILE_ID BINARY(16) The file ID of the parent directory.


Contains the null value if the file ID is not available or the object is
not in the "root" (/), QOpenSys, or user-defined file systems.

IMGCLGE_ACCESS_TYPE VARCHAR(10) Access type for the image catalog entry.

READ The file containing the image catalog entry is read-


only.

READ WRITE The file containing the image catalog entry is read/
write capable.

Contains the null value if the operation was against an image catalog
or the object type is not *IMGCLG.

IMGCLGE_INDEX_NUMBER INTEGER Index number of the image catalog entry.


Contains the null value if the operation was against an image catalog
or the object type is not *IMGCLG.

IMGCLGE_VOLUME_ID VARCHAR(32) Volume ID of the image catalog entry. Can contain the special value
*GEN.
Contains the null value if the operation was against an image catalog
or the object type is not *IMGCLG.

IMGCLGE_WRITE_PROTECTION VARCHAR(3) The write protection for the image catalog entry.

NO The file containing the image catalog entry is not write


protected.

YES The file containing the image catalog entry is write


protected..

Contains the null value if the operation was against an image catalog
or the object type is not *IMGCLG.

IMGCLGE_VIRTUAL_DEVICE VARCHAR(10) The name of the virtual device for the image catalog entry.
Contains the null value if the operation was against an image
catalog, the image catalog is not in Ready status, or the object type
is not *IMGCLG.

Example
• List objects in APPLIB that were read in the last 2 days.

Database performance and query optimization 783


SELECT COUNT(*), LIBRARY_NAME, OBJECT_NAME, OBJECT_TYPE FROM TABLE(
SYSTOOLS.AUDIT_JOURNAL_ZR(
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 2 DAYS
)
)
WHERE LIBRARY_NAME = 'APPLIB'
GROUP BY LIBRARY_NAME, OBJECT_NAME, OBJECT_TYPE;

DISPLAY_JOURNAL table function


The DISPLAY_JOURNAL table function returns information about journal entries. It returns information
similar to what is returned by the Display Journal (DSPJRN) CL command and the Retrieve Journal Entries
(QjoRetrieveJournalEntries) API.
Authorization:
• The caller must have *USE authority to the journal and *EXECUTE authority to the library containing the
journal.
• The caller must have *USE authority to every requested journal receiver and *EXECUTE authority to the
library containing the journal receiver.
• *OBJEXIST authority is required to the journal if object-name is omitted or if object-name specifies an
object that no longer exists.
• If object-name is *ALL, the caller must be authorized to every object associated with a journal entry.
– The caller must have:
- *USE authority to the object, and
- *EXECUTE authority to the library containing the object.

784 IBM i: Performance and Query Optimization


DISPLAY_JOURNAL ( journal-library ,
JOURNAL_LIBRARY =>

journal-name
JOURNAL_NAME =>

, receiver-library
STARTING_RECEIVER_LIBRARY =>

, receiver-name
STARTING_RECEIVER_NAME =>

, starting-timestamp
STARTING_TIMESTAMP =>

, starting-sequence
STARTING_SEQUENCE =>

, journal-codes
JOURNAL_CODES =>

, journal-types
JOURNAL_ENTRY_TYPES =>

, object-library
OBJECT_LIBRARY =>

, object-name
OBJECT_NAME =>

, object-type
OBJECT_OBJTYPE =>

, object-member
OBJECT_MEMBER =>

, user , job
USER => JOB =>

, program
PROGRAM =>

, ending-receiver-library
ENDING_RECEIVER_LIBRARY =>

, ending-receiver-name
ENDING_RECEIVER_NAME =>

, ending-timestamp
ENDING_TIMESTAMP =>

, ending-sequence
ENDING_SEQUENCE =>

, generate-syslog
GENERATE_SYSLOG =>

, eof-delay
EOF_DELAY =>

, commit-cycle
COMMIT_CYCLE =>

)
, include-internal
INCLUDE_INTERNAL =>

The schema is QSYS2.

journal- A character or graphic string expression that identifies the name of the library containing
library the journal. The name cannot be *LIBL or *CURLIB.

Database performance and query optimization 785


journal- A character or graphic string expression that identifies the name of the journal.
name
receiver- A character or graphic string expression that identifies the name of the starting journal
library receiver library. The name can be *LIBL or *CURLIB.
receiver- A character or graphic string expression that identifies the name of the starting journal
name receiver. If one of the special values is specified, the receiver-library value will be ignored.
Otherwise, the receiver-name and receiver-library must identify a valid journal receiver.
If no journal receiver is specified, *CURRENT is used.

*CURRENT The journal receiver that is currently attached when starting to convert
journal entries is used.
*CURCHAIN The journal receiver chain that includes the journal receiver that is
currently attached when starting to convert journal entries is used. This
receiver chain does not cross a break in the chain. If there is a break in
the chain, the receiver range is from the most recent break in the chain
through the receiver that is attached when starting to convert journal
entries.
*CURAVLCHN The journal receiver chain that includes the journal receiver that is
attached when starting to convert journal entries is used. This receiver
chain does not cross a break in the chain. If there is a break in the chain,
the receiver range is from the most recent break in the chain through
the receiver that is attached when starting to convert journal entries.
If journal receivers exist in the receiver chain that are not available
because they were saved with the storage freed option, those journal
receivers will be ignored and entries will be converted starting with the
first available journal receiver in the chain.
*CURSEQCHN The journal receiver chain that includes the journal receiver that is
attached when starting to convert journal entries is used, starting with
the most recent journal receiver in which the journal sequence number
was reset if the journal sequence number was reset in the receiver
chain. This receiver chain does not cross a break in the chain. If there is
a break in the chain, the receiver range is from the most recent break in
the chain through the receiver that is attached when starting to convert
journal entries. If journal receivers exist in the receiver chain that are
not available because they were saved with the storage freed option,
those journal receivers will be ignored and entries will be converted
starting with the first available journal receiver in the chain.

starting- A timestamp value that specifies the starting timestamp to use2.


timestamp
A value cannot be specified for both starting-timestamp and starting-sequence.
If no starting timestamp is specified, the earliest timestamp in the receiver range is used.

starting- A decimal expression that identifies the starting sequence number to use. If the starting-
sequence sequence value is not found in the receiver range, an error is returned.
A value cannot be specified for both starting-timestamp and starting-sequence.
If no starting sequence is specified, the first sequence number in the receiver range is
used.

2 The accuracy of the entry timestamp stored in journal receivers is only accurate to 16 microseconds.
Hence, a value passed as a starting_timestamp and ending_timestamp will be truncated such that the
actual timestamps being searched for may be from 0 to 15 microseconds less than the specified value.

786 IBM i: Performance and Query Optimization


journal- A character or graphic string expression that lists the journal codes to return. The string
codes can contain the special values of *ALL or *CTL, or it can be a list of one or more
journal codes. Journal codes in the string can be separated by one or more separators.
Separators are blank and comma. For example, a valid string can be 'RJ' or 'R J' or 'R,J' or
'R, J'.
If no string is provided, *ALL is used.

journal- A character or graphic string expression that lists the journal entry types to return. The
types string can contain the special values of *ALL or *RCD, or it can be a list of one or more
journal entry types. Journal entry types in the string can be separated by one or more
separators. Separators are blank and comma. For example, a valid string can be 'JFCT' or
'JF CT' or 'JF,CT' or 'JF, CT'.
If no string is provided, *ALL is used.

object- A character or graphic string expression that identifies the name of an object library. The
library values *LIBL and *CURLIB are allowed.
object-name A character or graphic string expression that contains up to 300 object names. Multiple
names can be separated by one or more separators. Separators are blank and comma.
If object-name is the special value of *ALL, object-library must contain a library name and
object-type must contain a valid object type. Otherwise, each object name must identify a
valid object using the same object-library, object-type, and object-member parameters.
If no object name is provided, a value of *ALLFILE is used for the journaled file name on
the API interface.

object-type A character or graphic string expression that identifies the system object type for the
object. The value must be *DTAARA, *DTAQ, *FILE, or *LIB.
object- A character or graphic string expression that identifies the name of a member. It can be a
member special value of *FIRST, *ALL, or *NONE or a valid member name. If the object type is not
*FILE, the member name is ignored.
user A character or graphic string expression that identifies the user profile name for the
current user of the job. If user is not specified, *ALL is used.
job A character or graphic string expression that identifies the name of a job. Two forms of a
job name are supported.
1. A fully qualified job name in the form job-number/job-user/job-name.
2. The first 10 characters are the job name, the second 10 characters are the user name,
and the last 6 characters are the job number.
If job is not specified, *ALL is used.
program A character or graphic string expression that identifies the name of a program. If program
is not specified, *ALL is used.
ending- A character or graphic string expression that identifies the name of the ending journal
receiver- receiver library. The name can be *LIBL or *CURLIB. If ending-receiver-name is not
library *CURRENT, a value for ending-receiver-library must be specified.
The value of this parameter is ignored if eof-delay is greater than zero.

ending- A character or graphic string expression that identifies the name of the ending journal
receiver- receiver. If the special value *CURRENT is specified, the ending-receiver-library value will
name be ignored. Otherwise, the ending-receiver-name and ending-receiver-library must identify
a valid journal receiver.
If ending-receiver-name is not specified, *CURRENT is used.
The value of this parameter is ignored if eof-delay is greater than zero.

Database performance and query optimization 787


ending- A timestamp value that specifies the ending timestamp to use2.
timestamp
A value cannot be specified for both ending-timestamp and ending-sequence. This
parameter cannot be specified if eof-delay is greater than zero.
If no ending timestamp is specified, the latest timestamp in the receiver range is used.

ending- A decimal expression that identifies the ending sequence number to use. If the ending-
sequence sequence value is not found in the receiver range, an error is returned.
A value cannot be specified for both ending-timestamp and ending-sequence. This
parameter cannot be specified if eof-delay is greater than zero.
If no ending sequence is specified, the last sequence number in the receiver range is
used.
When ending-sequence is used, the query results will end when the first ending sequence
value is encountered. If the journal has had its sequence numbers reset, ending-sequence
will only return results through the first match of ending-sequence.

generate- A character or graphic string expression that indicates whether to transform journal
syslog entries into syslog formatted detail. Values are:

NO No syslog information will be returned. The SYSLOG_EVENT,


SYSLOG_FACILITY, SYSLOG_SEVERITY, and SYSLOG_PRIORITY columns will
contain the null value.
RFC3164 Values will be returned for the SYSLOG_EVENT, SYSLOG_FACILITY,
SYSLOG_SEVERITY, and SYSLOG_PRIORITY columns if syslog information
is defined for the journal entry. The SYSLOG_EVENT column will contain a
syslog header that matches the RFC3164 format as described by the Internet
Engineering Task Force (IETF) Request For Comments (RFC) 3164.
RFC5424 Values will be returned for the SYSLOG_EVENT, SYSLOG_FACILITY,
SYSLOG_SEVERITY, and SYSLOG_PRIORITY columns if syslog information
is defined for the journal entry. The SYSLOG_EVENT column will contain a
syslog header that matches the RFC5424 format as described by the Internet
Engineering Task Force (IETF) Request For Comments (RFC) 5424.

DISPLAY_JOURNAL only returns syslog information for the audit journal. If RFC3164 or
RFC5424 is specified, journal-library must be QSYS and journal-name must be QAUDJRN.
If generate-syslog is not specified or is the null value, NO is used.

eof-delay An integer expression that specifies the number of seconds to sleep when all audit journal
entries have been read. This delay allows the caller to establish a polling service that will
continually return rows, sleeping for the specified interval whenever all entries have been
processed.
A value of zero indicates no delay is used and a finite set of rows will be returned. A value
greater than zero indicates that the table function will sleep, as needed, to wait for new
audit journal entries and never end. If eof-delay is not specified or is the null value, zero is
used.
If this parameter has a value greater than zero, the generate-syslog parameter must be
RFC3164 or RFC5424, the ending-receiver-library and ending-receiver-name are ignored,
and the ending-timestamp and ending-sequence parameters cannot be specified with a
value other than their default values.
When using a non-zero eof-delay parameter, avoid using query clauses that depend on
returning a finite number of rows. For example, using the FETCH FIRST n ROWS clause
can cause the query to end when the requested number of rows has been satisfied. A
query using the DISPLAY_JOURNAL function with a non-zero eof-delay parameter does

788 IBM i: Performance and Query Optimization


not allow data to be copied (ALWCPYDTA(*NO)). This means that a query requiring a
copy of data, such as one using an ORDER BY clause or UNION DISTINCT, will issue
an error and not be allowed. When using eof-delay, consider using a simple query to
avoid blocking of rows. When rows are blocked for data transport efficiency, rows won't
be returned until the block is full. Therefore, you should decide whether you favor data
transport efficiency or moving events as soon as they occur.

commit- A decimal expression that identifies the commit cycle identifier to use.
cycle
If commit-cycle is not specified, *ALL is used.

include- A character or graphic string expression that indicates whether to return hidden journal
internal entries. Hidden entries are generated and used by the system. When hidden entries
are returned, it is possible to display all journal entries so all sequence numbers are
accounted for.

NO Internal entries are not returned.


YES Internal entries are returned.

If include-internal is not specified, NO is used.

The special values supported for the function arguments are the same as for the Display Journal
(DSPJRN) CL command.
The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 191. DISPLAY_JOURNAL table function

Column Name Data Type Description

ENTRY_TIMESTAMP TIMESTAMP The system date and time when the journal entry was added to the journal
receiver2.

SEQUENCE_NUMBER DECIMAL(21,0) A number assigned by the system to each journal entry.

JOURNAL_CODE CHAR(1) The primary category of the journal entry.

JOURNAL_ENTRY_TYPE CHAR(2) Further identifies the type of user-created or system-created entry.

COUNT_OR_RRN BIGINT Contains either the relative record number (RRN) of the record that caused the
journal entry or a count that is pertinent to the specific type of journal entry.

ENTRY_DATA BLOB(2G) The entry specific data returned for this journal entry.
See Notes section for row and column access control considerations.

NULL_VALUE_INDICATORS VARCHAR(8000) The null value indicators returned for this journal entry.

OBJECT VARCHAR(30) The name of the object for which the journal entry was added.

OBJECT_TYPE VARCHAR(10) The type of object in the entry.

OBJECT_TYPE_INDICATOR CHAR(1) An indicator with respect to the information in the object field.

FILE_TYPE_INDICATOR CHAR(1) Identifies whether or not this journal entry is associated with a logical file.

JOURNAL_IDENTIFIER VARCHAR(10) The journal identifier (JID) for the object.

USER_NAME VARCHAR(10) The name of the effective user profile under which the job was running when the
entry was created.
This value is identical to what is returned in the CURRENT_USER column.

JOB_NAME VARCHAR(10) The name of the job that added the entry.

JOB_USER VARCHAR(10) The user profile name of the user that started the job.

JOB_NUMBER VARCHAR(6) The job number of the job that added the entry.

THREAD BIGINT Identifies the thread within the process that added the journal entry.

PROGRAM_NAME VARCHAR(10) The name of the program that added the entry.

PROGRAM_LIBRARY VARCHAR(10) The name of the library that contains the program that added the journal entry.

PROGRAM_LIBRARY_ASP_DEVICE VARCHAR(10) The name of the ASP device that contains the program.

Database performance and query optimization 789


Table 191. DISPLAY_JOURNAL table function (continued)

Column Name Data Type Description

PROGRAM_LIBRARY_ASP_NUMBER INTEGER The number for the auxiliary storage pool that contains the program that added
the journal entry.

COMMIT_CYCLE DECIMAL(21,0) A number that identifies the commit cycle.

NESTED_COMMIT_LEVEL BIGINT Indicates the nesting level of the commit cycle that was open when a journal
entry representing an object level change was deposited.

XID VARCHAR(140) The transaction identifier, as defined by the Open Group's XA specification, for
commit cycles related to an XA transaction branch.

LUW VARCHAR(39) The logical unit of work identifies entries to be associated with a given unit of
work.

REMOTE_PORT INTEGER The port number of the remote address associated with this journal entry.

REMOTE_ADDRESS VARCHAR(46) The remote address associated with the journal entry.

SYSTEM_NAME VARCHAR(8) The name of the system on which the entry is being retrieved.

SYSTEM_SEQUENCE_NUMBER DECIMAL(21,0) The system sequence number indicates the relative sequence of when this journal
entry was deposited into the journal.

REFERENTIAL_CONSTRAINT CHAR(1) Whether this entry was recorded for actions that occurred on records that are part
of a referential constraint.

TRIGGER CHAR(1) Whether this entry was created as result of a trigger program.

IGNORE_ON_APPLY CHAR(1) Whether this entry is ignored during an Apply Journaled Changes (APYJRNCHG) or
Remove Journaled Changed (RMVJRNCHG) command.

MINIMIZED_ENTRY_DATA CHAR(1) Whether this entry has minimized entry specific data as a result of the journal
having specified MINENTDTA for the object type of the entry.

MINIMIZED_ON_FIELD_BOUNDARY CHAR(1) Whether this entry has minimized entry specific data on field boundaries as a
result of the journal having been specified with MINENTDTA(*FLDBDY).

INDICATOR_FLAG CHAR(1) An indicator for the operation.

RECEIVER_NAME VARCHAR(10) The name of the receiver holding the journal entry.

RECEIVER_LIBRARY VARCHAR(10) The name of the library containing the receiver holding the journal entry.

RECEIVER_ASP_DEVICE VARCHAR(10) The name of the ASP device containing the receiver holding the journal entry.

RECEIVER_ASP_NUMBER INTEGER The number for the auxiliary storage pool containing the receiver holding the
journal entry.

ARM_NUMBER INTEGER The number of the disk arm that contains the journal entry.

OBJECT_ASP_DEVICE VARCHAR(10) ASP device name.

OBJECT_ASP_NUMBER INTEGER ASP number.

PARENT_FILE_ID BINARY(16) File ID for parent directory.

OBJECT_FILE_ID BINARY(16) File ID for object.

RELATIVE_DIRECTORY_FILE_ID BINARY(16) File ID of directory containing object in PATH_NAME.

OBJECT_FILE_NAME VARGRAPHIC(2002) Object name.


CCSID 1200

PATH_NAME DBCLOB(16M) Name of IFS path.


CCSID 1200

DLO_NAME VARCHAR(12) DLO name.

FOLDER_PATH VARCHAR(63) DLO folder path.

CURRENT_USER VARCHAR(10) The name of the effective user profile under which the job was running when the
entry was created.
This value is identical to what is returned in the USER_NAME column.

790 IBM i: Performance and Query Optimization


Table 191. DISPLAY_JOURNAL table function (continued)

Column Name Data Type Description

SYSLOG_EVENT VARGRAPHIC(2048) The Common Event Format (CEF) syslog event for the journal entry preceded with
CCSID 1200 a header of the requested type. If a header-type of RFC3164 is requested, the
maximum length is 1024 characters. If a header-type of RFC5424 is requested,
the maximum length is 2048 characters. The string will be truncated with no
warning if it exceeds the maximum length.
The audit journal entry types that generate syslog information and the key names
returned for journal entries are listed in the Notes section.
Contains the null value if there is no syslog event defined for the journal entry or if
NO was specified for the GENERATE_SYSLOG parameter.

SYSLOG_FACILITY INTEGER The syslog facility assigned to the event.

4 Security/authorization messages. This value is returned for all T and U audit


journal entries.

Contains the null value if there is no syslog event defined for the journal entry or if
NO was specified for the GENERATE_SYSLOG parameter.

SYSLOG_SEVERITY INTEGER The syslog severity assigned to the event.

2 Critical condition

4 Warning condition

5 Notice: A normal but significant condition

6 Informational message

The severity assigned to each journal entry is listed in the Notes section.
Contains the null value if there is no syslog event defined for the journal entry or if
NO was specified for the GENERATE_SYSLOG parameter.

SYSLOG_PRIORITY INTEGER The syslog priority number assigned to the event.


Contains the null value if there is no syslog event defined for the journal entry or if
NO was specified for the GENERATE_SYSLOG parameter.

Notes
Row and column access control: This table function recognizes whether ROW ACCESS CONTROL or
COLUMN ACCESS CONTROL exists and is activated for the target table. If any row or column access
control is active for the table, the rule text logic defined for the row permissions and/or column masks is
applied before returning the value in ENTRY_DATA. When the rule text for a row permission determines
that the user invoking the function should not see the row, the ENTRY_DATA column contains the text NOT
AUTHORIZED. If the user is allowed to see the row and a column mask exists, the rule text for the column
mask determines the value returned for ENTRY_DATA.
LOB data considerations: For journal code R (any entry type) and code F (IZ entry type), when a LOB data
type is encountered that is not a zero-length string, 16 'Q's are placed in the Entry Specific Data, followed
by the LOB data.
Filtering considerations: When using DISPLAY_JOURNAL to review journal activity for specific objects,
there are some considerations to ensure complete results are returned.
• When querying the audit journal (JOURNAL_LIBRARY => 'QSYS' and JOURNAL_NAME => 'QAUDJRN'),
do not use the object filters because they will result in no entries being returned. For an audit journal,
use a WHERE clause to limit the rows returned.
• When querying a data journal, consider whether it's possible that the Journal Identifier (JID) has
changed for the object. The object filters use the JID found in the object and will not return any entries
with a different JID. If the JID for the object might have changed, avoid using the object filters. In this
case, use a WHERE clause to limit the rows returned.
Syslog information: Syslog information is returned for all audit journal entries with T and U journal codes.
Syslog information is also available for history log messages. See HISTORY_LOG_INFO table function for
more details.
The following audit journal entries with T journal codes generate syslog information:

Database performance and query optimization 791


AD Auditing changes
AF Authority failure
AP Obtaining adopted authority
AU Attribute changes
AX Row and column access control
CA Authority changes
CD Command string audit
CO Create object
CP User profile changed, created, or restored
CQ Change of *CRQD object
CU Cluster operations
CV Connection verification
CY Cryptographic configuration
DI Directory server
DO Delete object
DS DST security password reset
EV System environment variables
GR Generic record
GS Socket description was given to another job
IM Intrusion monitor
IP Interprocess communication
IR IP rules actions
IS Internet security management
JD Change to user parameter of a job description
JS Actions that affect jobs
KF Key ring file
LD Link, unlink, or look up directory entry
ML Office services mail actions
M0 Db2 Mirror setup tools
M6 Db2 Mirror communication services
M7 Db2 Mirror replication services
M8 Db2 Mirror product services
M9 Db2 Mirror replication state
NA Network attribute changed
ND APPN directory search filter violation
NE APPN end point filter violation
OM Object move or rename
OR Object restore

792 IBM i: Performance and Query Optimization


OW Object ownership changed
O1 Optical access
O2 Optical access
O3 Optical access
PA Program changed to adopt authority
PF PTF operations
PG Change of an object’s primary group
PO Printed output
PS Profile swap
PU PTF object changes
PW Invalid password
RA Authority change during restore
RJ Restoring job description with user profile specified
RO Change of object owner during restore
RP Restoring adopted authority program
RQ Restoring a *CRQD object
RU Restoring user profile authority
RZ Changing a primary group during restore
SD Changes to system distribution directory
SE Subsystem routing entry changed
SF Actions to spooled files
SG Asynchronous signals
SK Sockets connections
SM Systems management changes
SO Server security user information actions
ST Use of service tools
SV System value changed
VO Validation list actions
VP Network password error
XD Directory server extension
X0 Network authentication
X1 Identity token
X2 Query manager profile changes
YC DLO object accessed (change)
YR DLO object accessed (read)
ZC Object accessed (change)
ZR Object accessed (read)

Audit journal entries with the U journal code are assigned a SYSLOG_SEVERITY of 6. The audit journal
entries with T journal codes are assigned a SYSLOG_SEVERITY value in the following way:

Database performance and query optimization 793


• Severity 2 Critical condition
– SV - System value when QAUDCTL is changed to *NONE
• – AF - Authority failure
– DI - Directory server (operation type 'AF')
– GR - Generic record, when function usage was checked and failed for a function name with a prefix of
QIBM_DB_
– IM - Intrusion monitor
– IP - Interprocess communication (entry type 'F')
• Severity 5 Notice: A normal but significant condition
– AD - Auditing changes
– AX - Row and column access control
– CA - Authority changes
– CP - User profile changed, created, or restored
– DI - Directory server (operation types 'AD', 'CA', 'CP', 'OM', 'OW', and 'PW')
– DS - DST security password reset
– IP - Interprocess communication (entry type 'A')
– JD - Change to user parameter of a job description
– JS - Actions that affect jobs (entry types 'M' and 'T')
– OM - Object move or rename
– OW - Object ownership changed
– O3 - Optical access (entry type 'L')
– PG - Change of an object’s primary group
– PS - Profile swap
– PW - Invalid password
– RA - Authority change during restore
– RO - Change of object owner during restore
– RU - Restoring user profile authority
– RZ - Change a primary group during restore
– SO - Server security user information actions
– VO - Validation list actions (entry type 'U')
– VP - Network password error
– X0 - Network authentication (entry types '2' - '6', '8', '9' and 'A' - 'F')
– X1 - Identity token (entry types 'F' and 'U')
– X2 - Query manager profile changes
• Severity 6 Informational message
– AP - Obtaining adopted authority
– AU - Attribute changes
– CD - Command string audit
– CO - Create object
– CQ - Change of *CRQD object
– CU - Cluster operations
– CV - Connection verification
– CY - Cryptographic configuration

794 IBM i: Performance and Query Optimization


– DI - Directory server (all operation types other than 'AD', 'AF', 'CA', 'CP', 'OM', 'OW', and 'PW')
– DO - Delete object
– EV - System environment variables
– GR - Generic record, except for the Severity 4 case where function usage was checked and failed
– GS - Socket description was given to another job
– IP - Interprocess communication (all entry types other than 'A' and 'F')
– IR - IP rules actions
– IS - Internet security management
– JS - Actions that affect jobs (all entry types other than 'M' and 'T')
– KF - Key ring file
– LD - Link, unlink, or look up directory entry
– ML - Office services mail actions
– M0 - Db2 Mirror setup tools
– M6 - Db2 Mirror communication services
– M7 - Db2 Mirror replication services
– M8 - Db2 Mirror product services
– M9 - Db2 Mirror replication state
– NA - Network attribute changed
– ND - APPN directory search filter violation
– NE - APPN end point filter violation
– OR - Object restore
– O1 - Optical access
– O2 - Optical access
– O3 - Optical access (all entry types other than 'L')
– PA - Program changed to adopt authority
– PF - PTF operations
– PO - Printed output
– PU - PTF object changes
– RJ - Restoring job description with user profile specified
– RP - Restoring adopted authority program
– RQ - Restoring a *CRQD object
– SD - Changes to system distribution directory
– SE - Subsystem routing entry changed
– SF - Actions to spooled files
– SG - Asynchronous signals
– SK - Sockets connections
– SM - Systems management changes
– ST - Use of service tools
– SV - System value changed, except for QAUDCTL severity 2 case
– VO - Validation list actions (all entry types other than 'U')
– XD - Directory server extension
– X0 - Network authentication (all entry types other than '2' - '6', '8', '9' and 'A' - 'F')
– X1 - Identity token (all entry types other than 'F' and 'U')

Database performance and query optimization 795


– YC - DLO object accessed (change)
– YR - DLO object accessed (read)
– ZC - Object accessed (change)
– ZR - Object accessed (read)
The Common Event Format key names that are generated within the SYSLOG_EVENT column are:

Table 192. Common Event Format key names


Common Event Format key name Description
attrName Attribute name (extracted from ENTRY_DATA
column)
attrValue Attribute value (extracted from ENTRY_DATA
column)
deviceExternalId Device name (extracted from ENTRY_DATA
column)
dloName Document Library Object name (DLO_NAME
column)
dloPath Document Library Object folder path
(FOLDER_PATH column)
dproc Destination job (process) name (extracted from
ENTRY_DATA column)
dpt Destination port number (extracted from
ENTRY_DATA column)
dst Destination IP address (extracted from
ENTRY_DATA column)
duser Destination user name (extracted from
ENTRY_DATA column)
filePath IFS stream file path (PATH_NAME column)
fileType Object type (OBJECT_TYPE column)
fname IFS stream file name (OBJECT_FILE_NAME
column)
msg Additional information from the audit record
not included in other keys (extracted from
ENTRY_DATA column)
objName Object name (OBJECT column)
oldAttrValue Attribute value (before change) (extracted from
ENTRY_DATA column)
oldDloName Document Library Object name (before rename)
(extracted from ENTRY_DATA column)
oldDloPath Document Library Object folder path (before
rename) (extracted from ENTRY_DATA column)
oldFileName IFS stream file name (before rename) (extracted
from ENTRY_DATA column)
oldFilePath IFS stream file path (before rename) (extracted
from ENTRY_DATA column)

796 IBM i: Performance and Query Optimization


Table 192. Common Event Format key names (continued)
Common Event Format key name Description
oldObjName Object name (before rename) (extracted from
ENTRY_DATA column)
reason Text description of the audit journal entry
shost Source system (host) name (SYSTEM_NAME
column)
sproc Source job (process) name (JOB_NAME,
JOB_USER, JOB_NUMBER columns)
spt Source port number (REMOTE_PORT column)
src Source IP address (REMOTE_ADDRESS column)
suser Source user name (USER_NAME column)

Examples
• Select all entries from the *CURRENT receiver of journal TESTLIB/QSQJRN.

SELECT * FROM TABLE (


QSYS2.DISPLAY_JOURNAL( 'TESTLIB', 'QSQJRN')) AS JT;

• Find all changes made by SUPERUSER against the PRODDATA/SALES table. The first two arguments
are passed without names since they correspond with the first two parameters for the function. The
other four arguments are passed using the parameter name syntax to avoid specifying a value for the
parameters that are not needed.

SELECT journal_code, journal_entry_type, object, object_type, X.*


FROM TABLE (
QSYS2.Display_Journal(
'PRODDATA', 'QSQJRN', -- Journal library and name
OBJECT_LIBRARY=>'PRODDATA', OBJECT_NAME=>'SALES',
OBJECT_OBJTYPE=>'*FILE', OBJECT_MEMBER=>'SALES'
) ) AS X
WHERE journal_entry_type in ('DL', 'PT', 'PX', 'UP') AND "CURRENT_USER" = 'SUPERUSER'
ORDER BY entry_timestamp DESC;

• Review audit journal entries for the REQUESTS file in MYCO library. For an audit journal, a predicate is
used to designate the object name.

SELECT journal_code, journal_entry_type, object, object_type, X.*


FROM TABLE (QSYS2.Display_Journal('QSYS', 'QAUDJRN') ) AS X
WHERE LEFT(OBJECT,20) = CHAR('REQUESTS', 10) CONCAT CHAR('MYCO', 10)
ORDER BY entry_timestamp DESC;

• Review changes from the last hour for the REQUESTS file in MYCO library using the current JID. This
query will only find entries where the JID of MYCO/REQUESTS *FILE is an exact match to the entry. It
filters for the following three journal codes:

D Database File Operation


F Database File Member Operation
R Operation on Specific Record

SELECT journal_code, journal_entry_type, object, object_type, X.*


FROM TABLE (QSYS2.Display_Journal('MYCO', 'QSQJRN',
JOURNAL_CODES => 'D,F,R',
STARTING_RECEIVER_NAME => '*CURCHAIN',
OBJECT_OBJTYPE=>'*FILE',
OBJECT_LIBRARY=>'MYCO',
OBJECT_NAME=>'REQUESTS',
OBJECT_MEMBER=>'*ALL'

Database performance and query optimization 797


) ) AS X
WHERE entry_timestamp > CURRENT TIMESTAMP - 1 HOUR
ORDER BY entry_timestamp DESC ;

• Review all changes from the last hour for the REQUESTS file in MYCO library, including any that might
have a different Journal ID (JID). To see entries for all JIDs, a predicate is used to designate the object
name.

SELECT journal_code, journal_entry_type, hex( journal_identifier ),


object, object_type, X.*
FROM TABLE (QSYS2.Display_Journal('MYCO', 'QSQJRN',
JOURNAL_CODES => 'D,F,R',
STARTING_RECEIVER_NAME => '*CURCHAIN'
) ) AS X
WHERE LEFT(OBJECT,20) = CHAR('REQUESTS', 10) CONCAT CHAR('MYCO', 10)
and entry_timestamp > CURRENT TIMESTAMP - 1 HOUR
ORDER BY entry_timestamp DESC ;

• Select entries from the audit journal that return syslog information and format them with an RFC5424
header.

SELECT syslog_facility, syslog_severity, syslog_event


FROM TABLE (QSYS2.DISPLAY_JOURNAL('QSYS', 'QAUDJRN',
GENERATE_SYSLOG =>'RFC5424'
) ) AS X
WHERE syslog_event IS NOT NULL;

JOURNAL_INFO view
The JOURNAL_INFO view contains information about journals, including remote journals.
The values returned for the columns in the view are closely related to the values returned by the Retrieve
Journal Information (QJORJRNI) API. Refer to the API for more detailed information.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the journal, and
• *OBJOPR and some data authority other than *EXECUTE to the journal
The following table describes the columns in the view. The system name is JRNINFO. The schema is
QSYS2.
Table 193. JOURNAL_INFO view

Column Name System Column Name Data Type Description

JOURNAL_NAME JRNNAME VARCHAR(10) The name of the journal.

JOURNAL_LIBRARY SYS_DNAME VARCHAR(10) The name of the library that contains the journal.

ASP_NUMBER ASPNUMBER INTEGER The number of the auxiliary storage pool to which
storage for the journal is allocated.

JOURNAL_ASPGRP JRNASPGRP VARCHAR(10) The name of the auxiliary storage pool (ASP) in
which the journal resides. A value of *SYSBAS
indicates the system ASP and all basic user ASPs.

ATTACHED_JOURNAL_RECEIVER_NAME ATTRCVNAME VARCHAR(10) The name of the journal receiver that is currently
attached to this journal.
Nullable
Contains the null value when there is no attached
receiver.

ATTACHED_JOURNAL_RECEIVER_LIBRARY ATTRCVLIB VARCHAR(10) The name of the library that contains the attached
journal receiver.
Nullable
Contains the null value when there is no attached
receiver.

MESSAGE_QUEUE MSGQNAME VARCHAR(10) The name of the message queue that is associated
with this journal.

MESSAGE_QUEUE_LIBRARY MSGQLIB VARCHAR(10) The name of the library that contains the message
queue.

798 IBM i: Performance and Query Optimization


Table 193. JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

DELETE_RECEIVER_OPTION DLTRCVOPT VARCHAR(3) Indicates whether the system deletes detached


journal receivers that are associated with this
journal when they are no longer needed for IPL or
IASP vary on recovery.

NO Detached journal receivers that are


associated with this journal are not
deleted when they are no longer needed
for IPL or IASP vary on recovery.

YES Detached journal receivers that are


associated with this journal are deleted
when they are no longer needed for IPL or
IASP vary on recovery.

DELETE_RECEIVER_DELAY DLTRCVDLY INTEGER The delay time (in minutes) between attempts
to delete journal receivers associated with this
Nullable journal.
Contains the null value when
DELETE_RECEIVER_OPTION is NO.

JOURNAL_TYPE TYPE VARCHAR(10) The scope of the journal and some of its
characteristics.

*LOCAL This is a local journal.

*REMOTE This is a remote journal.

JOURNAL_STATE STATE VARCHAR(10) An indication as to whether journal entries are


currently being sent to a journal. For a remote
journal, this is whether the journal is actively
receiving journal entries from the source system
journal.

*ACTIVE If this is a local journal, this


means journal entries can be
deposited to this journal. If this
is a remote journal, this means
journal entries can be received
from a source journal.

*CTLINACT The remote journal is in


the process of a controlled
inactivate.

*FAILED If this is a remote journal, this


means journal entries cannot be
received from a source journal
due to a remote journal function
failure. Does not apply to local
journals.

*INACTIVE If this is a remote journal, this


means journal entries cannot be
received from a source journal.

*INACTPEND If this is a remote journal,


this means a request is being
processed to set the journal
state to *INACTIVE. Does not
apply to local journals.

*PENDING The remote journal is


transitioning from an *INACTIVE
state to an *ACTIVE state.

*STANDBY If this is a local journal, this


means that most journal entries
are not deposited into the
journal and there will be no
errors indicating that the entry
was not deposited. Does not
apply to remote journals.

NUMBER_JOURNAL_RECEIVERS NUMJRNRCV INTEGER The total number of journal receivers that are
associated with the journal.

TOTAL_SIZE_JOURNAL_RECEIVERS SIZJRNRCV BIGINT The total size of the journal receivers (in kilobytes)
associated with the journal.

Database performance and query optimization 799


Table 193. JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

NUMBER_REMOTE_JOURNALS RMTJRNS INTEGER The total number of remote journals that are
directly downstream of this journal.

REDIRECTED_RECEIVER_LIBRARY RDRRCVLIB VARCHAR(10) For a local or *TYPE1 remote journal, the


redirected receiver library name that is currently
Nullable in place on this journal's local journal for any
downstream journal receivers associated with
*TYPE1 remote journals.
Contains *NONE if no *TYPE1 remote journals have
been added or if no receiver library redirection
was specified when *TYPE1 remote journals were
added.
Contains the redirected receiver library name that
is currently in place on this remote journal if the
specified journal is a *TYPE2 remote journal.
Contains the null value if no *TYPE1 remote
journals have been added.

MAXIMUM_REMOTE_JOURNALS_ MAXRMTENTB INTEGER The maximum number of entries that are waiting
ENTRIES_BEHIND to be sent to the target system for any remote
Nullable journal.
Contains the null value if
NUMBER_REMOTE_JOURNALS is 0 or if no
attached remote journals are active with async
delivery mode.

MAXIMUM_REMOTE_JOURNALS_ MAXRMTSECB BIGINT The maximum value (in hundredths of seconds)


TIME_BEHIND that the source journal is behind in sending journal
Nullable entries to the target system for any remote journal.
Contains the null value if
NUMBER_REMOTE_JOURNALS is 0 or if no
attached remote journals are active with async
delivery mode.

MAXIMUM_REMOTE_JOURNALS_ MAXRMTRETR BIGINT The maximum value for any remote journal
RETRANSMISSIONS of the total number of times the local
Nullable system retransmitted a segment because an
acknowledgement was not received.
Contains the null value if
NUMBER_REMOTE_JOURNALS is 0 or if no
attached remote journals are active using TCP/IP.

JOURNAL_TEXT TEXT VARCHAR(50) The text description of the journal.

Nullable Contains the null value if the journal has no text.

MANAGE_RECEIVER_OPTION MNGRCVOPT VARCHAR(10) Indicates whether the system or user manages the
changing of journal receivers.
Nullable
*SYSTEM The system manages the changing of
journal receivers.

*USER The user manages the changing of


journal receivers.

Contains the null value for a remote journal.

MANAGE_RECEIVER_DELAY MNGRCVDLY INTEGER The delay time (in minutes) between attempts to
attach new journal receivers to this journal.
Nullable
Contains the null value when
MANAGE_RECEIVER_OPTION is *USER or the null
value.

REMOVE_INTERNAL_ENTRIES RMVINTENT VARCHAR(3) Handling of internal system entries.

Nullable NO The internal system entries are not


removed.

YES The size of the attached receivers is


reduced by automatic removal of the
internal system entries.

Contains the null value for a remote journal.

800 IBM i: Performance and Query Optimization


Table 193. JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

REMOVE_FIXED_LENGTH_DETAIL MINFIXLEN VARCHAR(3) Handling of fixed length details.

Nullable NO Fixed length data is not removed.

YES The size of the journal entries that


are deposited into the attached journal
receivers is reduced by the automatic
removal of all fixed length data such as job
name, machine sequence number, and so
on.

Contains the null value for a remote journal.

RECEIVER_MAXIMUM_SIZE MAXOPT VARCHAR(10) The receiver size option that applies to this journal
receiver.
Nullable
*MAXOPT1 The journal receivers attached
to the journal can have a
maximum receiver size of
approximately one terabyte
(1,099,511,627,776 bytes) and a
maximum sequence number of
9,999,999,999. Additionally, the
maximum size of the journal
entry that can be deposited is
15,761,440 bytes.

*MAXOPT2 The journal receivers attached


to the journal can have a
maximum receiver size of
approximately one terabyte
(1,099,511,627,776 bytes) and a
maximum sequence number of
9,999,999,999. Additionally, the
maximum size of the journal
entry which can be deposited is
4,000,000,000 bytes.

*MAXOPT3 The journal receivers attached


to the journal can have a
maximum receiver size of
approximately one terabyte
(1,099,511,627,776 bytes) and
a maximum sequence number
of 18,446,744,073,709,551,600.
Additionally, the maximum size of
the journal entry which can be
deposited is 4,000,000,000 bytes.

*NONE The journal receivers attached


to the journal can have a
maximum journal receiver size of
approximately 1.9 gigabytes and
a maximum sequence number of
2,147,483,136.

Contains the null value for a remote journal.

MINIMIZE_ESD_FOR_DATA_AREAS MINDTAARA VARCHAR(3) Indicates whether journal entries for data areas
may have minimized entry specific data.
Nullable
NO Journal entries for data areas do not have
minimized entry specific data.

YES Journal entries for data areas have


minimized entry specific data.

Contains the null value for a remote journal.

Database performance and query optimization 801


Table 193. JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

MINIMIZE_ESD_FOR_FILES MINFILE VARCHAR(19) Indicates whether journal entries for files may
have minimized entry specific data.
Nullable
MINIMIZED Journal entries for files may
have minimized entry specific
data. The minimizing does
not occur on field boundaries.
Therefore, the entry specific
data may not be viewable and
may not be used for auditing
purposes.

MINIMIZED Journal entries for files may


FOR AUDIT have minimized entry specific
data. The minimizing occurs
on field boundaries. Therefore,
the entry specific data will be
viewable and may be used for
auditing purposes.

NO Journal entries for files will have


complete entry specific data.

Contains the null value for a remote journal.

JOURNAL_CACHE JRNCACHE VARCHAR(3) Specifies whether journal entries are cached


before being written out to disk.
Nullable
NO Journal entries are not cached before
being written out to disk.

YES Journal entries are cached before being


written out to disk.

Contains the null value for a remote journal.

FIXED_LENGTH_DATA_INCLUDES_ FLDJOB VARCHAR(3) Indicates whether the job name will be stored
JOB_NAME when journal entries are deposited.
Nullable
NO The job name will not be stored when
journal entries are deposited.

YES The job name will be stored when journal


entries are deposited.

Contains the null value for a remote journal.

FIXED_LENGTH_DATA_INCLUDES_ FLDUSR VARCHAR(3) Indicates whether the user name will be stored
USER_NAME when journal entries are deposited.
Nullable
NO The user name will not be stored when
journal entries are deposited.

YES The user name will be stored when journal


entries are deposited.

Contains the null value for a remote journal.

FIXED_LENGTH_DATA_INCLUDES_ FLDPGM VARCHAR(3) Indicates whether the program name will be


PROGRAM_NAME stored when journal entries are deposited.
Nullable
NO The program name will not be stored when
journal entries are deposited.

YES The program name will be stored when


journal entries are deposited.

Contains the null value for a remote journal.

FIXED_LENGTH_DATA_INCLUDES_ FLDPGMLIB VARCHAR(3) Indicates whether the program library name will
PROGRAM_LIBRARY be stored when journal entries are deposited.
Nullable
NO The program library name will not be
stored when journal entries are deposited.

YES The program library name will be stored


when journal entries are deposited.

Contains the null value for a remote journal.

802 IBM i: Performance and Query Optimization


Table 193. JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

FIXED_LENGTH_DATA_INCLUDES_ FLDSYSSEQ VARCHAR(3) Indicates whether the system sequence number


SYSTEM_SEQUENCE_NUMBER will be stored when journal entries are deposited.
Nullable
NO The system sequence number will not be
stored when journal entries are deposited.

YES The system sequence number will be


stored when journal entries are deposited.

Contains the null value for a remote journal.

FIXED_LENGTH_DATA_INCLUDES_ FLDRMTADR VARCHAR(3) Indicates whether the remote address will be


REMOTE_ADDRESS stored when journal entries are deposited.
Nullable
NO The remote address will not be stored
when journal entries are deposited.

YES The remote address will be stored when


journal entries are deposited.

Contains the null value for a remote journal.

FIXED_LENGTH_DATA_INCLUDES_ FLDTHD VARCHAR(3) Indicates whether the thread identifier will be


THREAD_ID stored when journal entries are deposited.
Nullable
NO The thread identifier will not be stored
when journal entries are deposited.

YES The thread identifier will be stored when


journal entries are deposited.

Contains the null value for a remote journal.

FIXED_LENGTH_DATA_INCLUDES_ FLDLUW VARCHAR(3) Indicates whether the logical unit of work identifier
LOGICAL_UNIT_OF_WORK_ID will be stored when journal entries are deposited.
Nullable
NO The logical unit of work identifier will
not be stored when journal entries are
deposited.

YES The logical unit of work identifier will be


stored when journal entries are deposited.

Contains the null value for a remote journal.

FIXED_LENGTH_DATA_INCLUDES_ FLDXID VARCHAR(3) Indicates whether the transaction identifier will be


TRANSACTION_ID stored when journal entries are deposited.
Nullable
NO The transaction identifier will not be stored
when journal entries are deposited.

YES The transaction identifier will be stored


when journal entries are deposited.

Contains the null value for a remote journal.

JOURNALED_OBJECT_LIMIT JRNOBJLMT VARCHAR(10) The number of objects that can be journaled to the
journal.
Nullable
*MAX250K The maximum number of objects
that can be journaled to the journal
is 250,000.

*MAX10M The maximum number of objects


that can be journaled to the journal
is 10,000,000.

Contains the null value for a remote journal.

JOURNALED_OBJECTS JRNALL INTEGER Total of all objects journaled to the journal.


This count includes explicitly journaled objects
Nullable such as files, file members, access paths, data
areas, data queues, libraries, and integrated file
system objects. This count also includes implicitly
journaled objects such as journal receivers,
commitment definitions, and objects journaled for
system recovery purposes.
Contains the null value for a remote journal.

Database performance and query optimization 803


Table 193. JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

JOURNALED_FILES JRNFILE INTEGER The total number of files that are currently being
journaled to this journal.
Nullable
Contains the null value for a remote journal.

JOURNALED_MEMBERS JRNMBR INTEGER The total number of file members that are
currently being journaled to this journal.
Nullable
Contains the null value for a remote journal.

JOURNALED_DATA_AREAS JRNDTAARA INTEGER The total number of data areas that are currently
being journaled to this journal.
Nullable
Contains the null value for a remote journal.

JOURNALED_DATA_QUEUES JRNDTAQ INTEGER The total number of data queues that are currently
being journaled to this journal.
Nullable
Contains the null value for a remote journal.

JOURNALED_IFS_OBJECTS JRNIFS INTEGER The total number of integrated file system objects
of type *DIR, *STMF, and *SYMLNK that are
Nullable currently being journaled to this journal.
Contains the null value for a remote journal.

JOURNALED_ACCESS_PATHS JRNAP INTEGER The total number of access paths that are currently
being journaled to this journal.
Nullable
Contains the null value for a remote journal.

JOURNALED_COMMITMENT_DEFINITIONS JRNCMTDFN INTEGER The total number of commitment definitions that


are currently being implicitly journaled to this
Nullable journal.
Contains the null value for a remote journal.

JOURNALED_LIBRARIES JRNLIB INTEGER The total number of libraries that are currently
being journaled to this journal.
Nullable
Contains the null value for a remote journal.

JOURNAL_RECOVERY_COUNT JRNRCYCNT INTEGER The approximate number of journaled changes


that would need to be recovered during journal
Nullable synchronization for this journal in the event of an
abnormal IPL or vary on.
Contains the null value for a local journal with the
value *SYSDFT or for a remote journal.

REMOTE_JOURNAL_TYPE RMTJRNTYPE VARCHAR(10) The type of remote journal. Values are *TYPE1 and
*TYPE2.
Nullable
Contains the null value for a local journal.

JOURNAL_DELIVERY_MODE DELIVMODE VARCHAR(10) The journal delivery mode that is being used to
replicate journal entries to this journal.
Nullable
*ASYNC Journal entries are being
delivered or replicated
asynchronously.

*ASYNCPEND Journal entries are to


be delivered or replicated
asynchronously, but the journal
is currently in catch-up mode.

*SYNC Journal entries are being


delivered or replicated
synchronously.

*SYNCPEND Journal entries are to


be delivered or replicated
synchronously, but the journal is
currently in catch-up mode.

Contains the null value for a local journal or a


remote journal whose JOURNAL_STATE field is not
*ACTIVE or *CTLINACT.

804 IBM i: Performance and Query Optimization


Table 193. JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

LOCAL_JOURNAL_NAME LCLJRNNAME VARCHAR(10) The journal name of the local journal. The local
journal is the journal that is the initiator of the
Nullable original journal deposit that has been replicated
downstream to this journal.
Contains the null value for a local journal.

LOCAL_JOURNAL_LIBRARY LCLJRNLIB VARCHAR(10) The library name of the local journal.

Nullable Contains the null value for a local journal.

LOCAL_JOURNAL_SYSTEM LCLJRNSYS VARCHAR(8) The name of the system for the local journal.

Nullable Contains *UNKNOWN if journal is a remote journal


and does not have an attached receiver.
Contains the null value for a local journal.

LOCAL_JOURNAL_ASPGRP LCLASPGRP VARCHAR(10) The name of the independent auxiliary storage


pool (ASP) group of the local journal. *SYSBAS is
Nullable used to indicate the system ASP and all basic user
ASPs.
Contains *UNKNOWN if journal is a remote journal
and does not have an attached receiver.
Contains the null value for a local journal.

SOURCE_JOURNAL_NAME SRCJRNNAME VARCHAR(10) The journal name of the source journal. The source
journal is the journal that is directly upstream of
Nullable this journal.
Contains *UNKNOWN if journal is a remote journal
and does not have an attached receiver.
Contains the null value for a local journal.

SOURCE_JOURNAL_LIBRARY SRCJRNLIB VARCHAR(10) The library name of the source journal.

Nullable Contains *UNKNOWN if journal is a remote journal


and does not have an attached receiver.
Contains the null value for a local journal.

SOURCE_JOURNAL_SYSTEM SRCJRNSYS VARCHAR(8) The name of the system for the source journal.

Nullable Contains *UNKNOWN if journal is a remote journal


and does not have an attached receiver.
Contains the null value for a local journal.

SOURCE_JOURNAL_ASPGRP SRCASPGRP VARCHAR(10) The name of the independent auxiliary storage


pool (ASP) group of the source journal.
Nullable
Contains *UNKNOWN if journal is a remote journal
and does not have an attached receiver.
Contains the null value for a local journal.

LOCAL_RECEIVER_SYSTEM LCLRCVSYS VARCHAR(8) If this journal receiver is associated with a remote


journal, the name of the system for the local
Nullable journal.
Contains *UNKNOWN if journal is a remote journal
and does not have an attached receiver.
Contains the null value for a local journal.

SOURCE_RECEIVER_SYSTEM SRCRCVSYS VARCHAR(8) If this journal receiver is associated with a remote


journal, the name of the system for the source
Nullable journal.
Contains *UNKNOWN if journal is a remote journal
and does not have an attached receiver.
Contains the null value for a local journal.

ACTIVATION_TIME ACTDT TIMESTAMP If the journal is a remote journal and it is currently


active, the date and time the journal was activated.
Nullable
Contains the null value for a local journal or a
remote journal whose JOURNAL_STATE field is not
*ACTIVE or *CTLINACT.

Database performance and query optimization 805


Table 193. JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

ESTIMATED_TIME_BEHIND ESTBEHIND BIGINT If the journal is an active remote journal and


the delivery mode is asynchronous, this is
Nullable the estimated amount of time, in milliseconds,
between when the journal entries are written to
disk on the source system and when they are
received on the target system.
Contains the null value for a local journal or a
remote journal whose JOURNAL_STATE field is not
*ACTIVE or *CTLINACT.

MAXIMUM_TIME_BEHIND MAXBEHIND BIGINT The maximum value of ESTIMATED_TIME_BEHIND


since the journal was activated.
Nullable
Contains the null value for a local journal or a
remote journal whose JOURNAL_STATE field is not
*ACTIVE or *CTLINACT.

MAXIMUM_BEHIND_TIMESTAMP MAXBHNDTIM TIMESTAMP The date and time that the


ESTIMATED_TIME_BEHIND occurred.
Nullable
Contains the null value for a local journal or a
remote journal whose JOURNAL_STATE field is not
*ACTIVE or *CTLINACT.

JOURNAL_ENTRY_FILTERING FILTER VARCHAR(3) Indicates whether or not journal entry filtering is


active for this journal.
Nullable
NO Journal entry filtering is not active for this
journal.

YES Journal entry filtering is active for this


journal.

Contains the null value for a local journal or a


remote journal whose JOURNAL_STATE field is not
*ACTIVE or *CTLINACT.

Examples
• List all journals that are falling behind sending entries to one or more remote journals:

SELECT JOURNAL_NAME, JOURNAL_LIBRARY,


MAXIMUM_REMOTE_JOURNALS_ENTRIES_BEHIND,
MAXIMUM_REMOTE_JOURNALS_TIME_BEHIND, MAXIMUM_REMOTE_JOURNALS_RETRANSMISSIONS
FROM QSYS2.JOURNAL_INFO
WHERE MAXIMUM_REMOTE_JOURNALS_ENTRIES_BEHIND > 0
ORDER BY MAXIMUM_REMOTE_JOURNALS_ENTRIES_BEHIND DESC

• Find any remote journals that are not currently active:

SELECT * FROM QSYS2.JOURNAL_INFO


WHERE JOURNAL_TYPE = '*REMOTE'
AND JOURNAL_STATE <> '*ACTIVE'
ORDER BY JOURNAL_LIBRARY, JOURNAL_NAME,

• For security auditing reasons, find any journals that are not recording remote address info:

SELECT * FROM QSYS2.JOURNAL_INFO


WHERE REMOVE_FIXED_LENGTH_DETAIL = 'YES'
OR FIXED_LENGTH_DATA_INCLUDES_REMOTE_ADDRESS = 'NO'

JOURNAL_RECEIVER_INFO view
The JOURNAL_RECEIVER_INFO view contains information about all journal receivers on the system.
The values returned for the columns in the view are closely related to the values returned by the Retrieve
Journal Receiver Information (QjoRtvJrnReceiverInformation) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the journal receiver, and

806 IBM i: Performance and Query Optimization


• *OBJOPR authority and some data authority other than *EXECUTE to the journal receiver.
If the journal receiver is associated with a journal, the caller requires:
• *EXECUTE authority to the library containing the journal, and
• *OBJOPR authority to the journal.
The following table describes the columns in the view. The system name is JRNRCV_INF. The schema is
QSYS2.
Table 194. JOURNAL_RECEIVER_INFO view

System Column Name


Column Name Data Type Description

JOURNAL_RECEIVER_LIBRARY JRNRCV_LIB VARCHAR(10) The name of the library that contains the journal
receiver.

JOURNAL_RECEIVER_NAME JRNRCV VARCHAR(10) The name of the journal receiver.

DESCRIPTIVE_TEXT TEXT VARCHAR(50) The text description of the journal receiver.


Nullable

JOURNAL_RECEIVER_ASP_NUMBER RCV_ASPNUM INTEGER The number of the auxiliary storage pool to which
storage for the journal receiver is allocated.

JOURNAL_RECEIVER_ASP_NAME RCV_ASPNAM VARCHAR(10) The name of the auxiliary storage pool (ASP) in
which the journal receiver resides. A value of
*SYSBAS indicates the system ASP or a basic user
ASP.

JOURNAL_LIBRARY JRN_LIB VARCHAR(10) The name of the library that contains the journal.
Nullable Contains the null value if the receiver has never
been attached to a journal.

JOURNAL_NAME JOURNAL VARCHAR(10) The name of the journal that the journal receiver is
Nullable attached to or used to be attached to.
Contains the null value if the receiver has never
been attached to a journal.

THRESHOLD THRESHOLD INTEGER An auxiliary disk storage space threshold value


Nullable (in kilobytes) for the journal receiver. If the
threshold value is exceeded during journaling and
the journal has the MNGRCV(*USER) attribute, a
message (CPF7099) is sent to the message queue
that is specified on the Create Journal (CRTJRN)
or the Change Journal (CHGJRN) command. If
the journal has the MNGRCV(*SYSTEM) attribute,
the system creates and attaches a new journal
receiver, detaches the old journal receiver when
the threshold is reached, and sends message
CPF7020 to the journal message queue.
Contains the null value for remote journal
receivers.

SIZE SIZE INTEGER The number of kilobytes of auxiliary disk storage


used by this journal receiver.

Database performance and query optimization 807


Table 194. JOURNAL_RECEIVER_INFO view (continued)

System Column Name


Column Name Data Type Description

STATUS STATUS VARCHAR(8) The status of the journal receiver.

ATTACHED The journal receiver is currently


attached to the journal.

ONLINE The journal receiver is online.


The journal receiver has not been
saved, and it has been detached
from the journal.

SAVED The journal receiver was saved


after it was detached. The journal
receiver storage was not freed
when it was saved.

FREED The journal receiver was saved


after it was detached. The journal
receiver storage was freed when it
was saved.

PARTIAL The journal receiver status is partial


for one of the following reasons:
• It was restored from a version
that was saved while it
was attached to the journal.
Additional journal entries may
have been written that were not
restored.
• It is associated with a remote
journal and it does not contain
all the journal entries that are
in the associated journal receiver
attached to the source journal.

EMPTY The journal receiver has never been


attached to a journal.

NUMBER_OF_JOURNAL_ENTRIES ENTRIES DECIMAL(20,0) The number of journal entries that are contained in
Nullable this journal receiver.
Contains the null value if STATUS is EMPTY.

FIRST_SEQUENCE_NUMBER FIRST_SEQ DECIMAL(21,0) The journal sequence number of the first journal
Nullable entry in this journal receiver.
Contains the null value if STATUS is EMPTY.

LAST_SEQUENCE_NUMBER LAST_SEQ DECIMAL(21,0) The journal sequence number of the last journal
Nullable entry in this journal receiver.
Contains the null value if STATUS is EMPTY.

MAXIMUM_ENTRY_SPECIFIC_DATA_LENGTH MAX_ESD DECIMAL(20,0) The length in bytes of the longest entry-specific


Nullable data among all journal entries in this journal
receiver.
Contains the null value if STATUS is EMPTY.

MAXIMUM_NULL_VALUE_INDICATORS MAX_NVI INTEGER The maximum number of null value indicators


Nullable among all journal entries in this journal receiver.
Contains the null value if STATUS is EMPTY.

ATTACH_TIMESTAMP ATTACHED TIMESTAMP(0) The date and time that this journal receiver was
Nullable attached to the journal. For a journal receiver
attached to a remote journal, this is the date and
time that the journal receiver was attached on the
local system.
Contains the null value if STATUS is EMPTY.

DETACH_TIMESTAMP DETACHED TIMESTAMP(0) The date and time that this journal receiver was
Nullable detached from the journal. For a journal receiver
attached to a *REMOTE journal, this is the date and
time that the journal receiver was detached on the
local system.
Contains the null value if STATUS is EMPTY,
ATTACHED, or PARTIAL.

808 IBM i: Performance and Query Optimization


Table 194. JOURNAL_RECEIVER_INFO view (continued)

System Column Name


Column Name Data Type Description

SAVE_TIMESTAMP SAVED TIMESTAMP(0) The date and time that the journal receiver was
Nullable last saved. This value reflects when the receiver
was saved from the system it exists on (either the
source or target system time).
Contains the null value if the journal receiver was
never saved.

PREVIOUS_JOURNAL_RECEIVER_LIBRARY PREV_RCVL VARCHAR(10) The name of the library of the previous journal
Nullable receiver that is associated with the same journal.
Contains the null value if STATUS is EMPTY, if there
was no journal receiver attached to the journal
prior to this journal receiver, or if it is currently
associated with a remote journal.

PREVIOUS_JOURNAL_RECEIVER PREV_RCV VARCHAR(10) The name of the previous journal receiver that is
Nullable associated with the same journal.
Contains the null value if STATUS is EMPTY, if there
was no journal receiver attached to the journal
prior to this journal receiver, or if it is currently
associated with a remote journal.

NEXT_JOURNAL_RECEIVER_LIBRARY NEXT_RCVL VARCHAR(10) The name of the library of the next journal receiver
Nullable that is associated with the same journal.
v

NEXT_JOURNAL_RECEIVER NEXT_RCV VARCHAR(10) The name of the next journal receiver that is
Nullable associated with the same journal.
v

Database performance and query optimization 809


Table 194. JOURNAL_RECEIVER_INFO view (continued)

System Column Name


Column Name Data Type Description

RECEIVER_MAXIMUM_SIZE MAXOPT pendin The journal receiver sequence number and size
option for this journal receiver. If this journal
VARCHAR(8) receiver is attached to a remote journal, the value
Nullable is determined by the local journal.

*NONE The journal receiver has a


maximum journal receiver size of
approximately 1.9 gigabytes and
a maximum sequence number of
2,147,483,136.

*MAXOPT1 The journal receiver has a


maximum journal receiver size
of approximately one terabyte
(1,099,511,627,776 bytes) and a
maximum sequence number of
9,999,999,999. Additionally, the
maximum size of the journal
entry that can be deposited is
15,761,440 bytes. This occurs if
this receiver was attached when
RCVSIZOPT(*MAXOPT1) was in
effect for the journal.

*MAXOPT2 The journal receiver has a


maximum journal receiver size
of approximately one terabyte
(1,099,511,627,776 bytes) and
a maximum sequence number
of 9,999,999,999. This occurs if
this receiver was attached when
RCVSIZOPT(*MAXOPT2) was in
effect for the journal. Additionally,
the maximum size of the journal
entry which can be deposited is
4,000,000,000 bytes.

*MAXOPT3 The journal receiver has a


maximum journal receiver size
of approximately one terabyte
(1,099,511,627,776 bytes) and
a maximum sequence number
of 18,446,744,073,709,551,600.
This occurs if this
receiver was attached when
RCVSIZOPT(*MAXOPT3) was in
effect for the journal. Additionally,
the maximum size of the journal
entry which can be deposited is
4,000,000,000 bytes.

Contains the null value if STATUS is EMPTY.

MINIMIZE_ESD_FOR_DATA_AREAS MINDTAARA VARCHAR(3) Whether the entry-specific data for data areas is
Nullable minimized. If this journal receiver is attached to a
remote journal, the value for is determined by the
local journal.

NO Journal entries for data areas have


complete entry specific data.

YES Journal entries for data areas may have


minimized entry specific data.

Contains the null value if STATUS is EMPTY.

810 IBM i: Performance and Query Optimization


Table 194. JOURNAL_RECEIVER_INFO view (continued)

System Column Name


Column Name Data Type Description

MINIMIZE_ESD_FOR_FILES MINFILE VARCHAR(6) Whether the entry-specific data for files is


Nullable minimized. If this journal receiver is attached to
a remote journal, the value is determined by the
local journal.

FLDBDY Journal entries for files may have


minimized entry specific data. The
minimizing occurs on field boundaries.
Therefore, the entry specific data will
be viewable and may be used for
auditing purposes.

NO Journal entries for files have complete


entry specific data.

YES Journal entries for files may have


minimized entry specific data. The
minimizing does not occur on field
boundaries. Therefore, the entry
specific data may not be viewable
and may not be used for auditing
purposes.

Contains the null value if STATUS is EMPTY.

FIXED_LENGTH_DATA_INCLUDES_JOB_NAME FLDJOB VARCHAR(3) Indicates whether the job name is stored when
Nullable journal entries are deposited.

NO The job name is not stored when journal


entries are deposited.

YES The job name is stored when journal


entries are deposited.

Contains the null value if STATUS is EMPTY.

FIXED_LENGTH_DATA_INCLUDES_USER_NAME FLDUSR VARCHAR(3) Indicates whether the user name is stored when
Nullable journal entries were deposited.

NO The user name is not stored when journal


entries are deposited.

YES The user name is stored when journal


entries are deposited.

Contains the null value if STATUS is EMPTY.

FIXED_LENGTH_DATA_INCLUDES_ FLDPGM VARCHAR(3) Indicates whether the program name is stored


PROGRAM_NAME Nullable when journal entries were deposited.

NO The program name is not stored when


journal entries are deposited.

YES The program name is stored when journal


entries are deposited.

Contains the null value if STATUS is EMPTY.

FIXED_LENGTH_DATA_INCLUDES_ FLDPGMLIB VARCHAR(3) Indicates whether the program library name is


PROGRAM_LIBRARY Nullable stored when journal entries were deposited.

NO The program library name is not stored


when journal entries are deposited.

YES The program library name is stored when


journal entries are deposited.

Contains the null value if STATUS is EMPTY.

FIXED_LENGTH_DATA_INCLUDES_ FLDSYSSEQ VARCHAR(3) Indicates whether the system sequence number is


SYSTEM_SEQUENCE_NUMBER Nullable stored when journal entries were deposited.

NO The system sequence number is not stored


when journal entries are deposited.

YES The system sequence number is stored


when journal entries are deposited.

Contains the null value if STATUS is EMPTY.

Database performance and query optimization 811


Table 194. JOURNAL_RECEIVER_INFO view (continued)

System Column Name


Column Name Data Type Description

FIXED_LENGTH_DATA_INCLUDES_ FLDRMTADR VARCHAR(3) Indicates whether the remote address is stored


REMOTE_ADDRESS Nullable when journal entries were deposited.

NO The remote address is not stored when


journal entries are deposited.

YES The remote address is stored when journal


entries are deposited.

Contains the null value if STATUS is EMPTY.

FIXED_LENGTH_DATA_INCLUDES_THREAD_ID FLDTHD VARCHAR(3) Indicates whether the thread identifier is stored


Nullable when journal entries were deposited.

NO The thread identifier is not stored when


journal entries are deposited.

YES The thread identifier is stored when journal


entries are deposited.

Contains the null value if STATUS is EMPTY.

FIXED_LENGTH_DATA_INCLUDES_ FLDLUW VARCHAR(3) Indicates whether the logical unit of work identifier
LOGICAL_UNIT_OF_WORK_ID Nullable is stored when journal entries were deposited.

NO The logical unit of work identifier is not


stored when journal entries are deposited.

YES The logical unit of work identifier is stored


when journal entries are deposited.

Contains the null value if STATUS is EMPTY.

FIXED_LENGTH_DATA_INCLUDES_ FLDXID VARCHAR(3) Indicates whether the transaction identifier is


TRANSACTION_ID Nullable stored when journal entries were deposited.

NO The transaction identifier is not stored


when journal entries are deposited.

YES The transaction identifier is stored when


journal entries are deposited.

Contains the null value if STATUS is EMPTY.

PENDING_TRANSACTIONS PEND_TRANS VARCHAR(3) Whether the journal receiver contains journal


Nullable entries for commitment control transactions that
have not yet been committed or rolled back.

NO The journal receiver does not contain


entries for pending commitment control
transactions.

YES The journal receiver contains entries for


pending commitment control transactions.

Contains the null value if STATUS is EMPTY or the


journal receiver was attached to a remote journal.

REMOTE_JOURNAL_TYPE RMT_TYPE VARCHAR(6) If this journal receiver was attached to a remote


Nullable journal, this is the remote journal type for that
journal when this journal receiver was attached.
Values are *TYPE1 and *TYPE2.
Contains the null value if the journal receiver was
not attached to a remote journal.

LOCAL_JOURNAL_SYSTEM LCLJRNSYS VARCHAR(8) The system name of the local journal. The local
Nullable journal is the journal that is the initiator of the
original journal deposit that has been replicated
downstream to this journal.
Contains the null value if the journal receiver was
not attached to a remote journal.

LOCAL_JOURNAL_LIBRARY LCLJRNLIB VARCHAR(10) The library name of the local journal.


Nullable Contains the null value if the journal receiver was
not attached to a remote journal.

812 IBM i: Performance and Query Optimization


Table 194. JOURNAL_RECEIVER_INFO view (continued)

System Column Name


Column Name Data Type Description

LOCAL_JOURNAL_NAME LCLJRNNAME VARCHAR(10) The name of the local journal. The local journal
Nullable is the journal that is the initiator of the
original journal deposit that has been replicated
downstream to this journal.
Contains the null value if the journal receiver was
not attached to a remote journal.

LOCAL_JOURNAL_ASP_GROUP LCLASPGRP VARCHAR(10) The independent auxiliary storage pool (IASP)


Nullable group of the local journal.
Contains the null value if the journal receiver was
not attached to a remote journal.

LOCAL_JOURNAL_RECEIVER_LIBRARY LCLRCVLIB VARCHAR(10) The library name of the journal receiver that is
Nullable associated with the local journal.
Contains the null value if the journal receiver was
not attached to a remote journal.

SOURCE_JOURNAL_SYSTEM SRCJRNSYS VARCHAR(8) The system name of the source journal.


Nullable Contains the null value if the journal receiver was
not attached to a remote journal.

SOURCE_JOURNAL_LIBRARY SRCJRNLIB VARCHAR(10) The library name of the source journal.


Nullable Contains the null value if the journal receiver was
not attached to a remote journal.

SOURCE_JOURNAL_NAME SRCJRNNAME VARCHAR(10) The name of the source journal. The source journal
Nullable is the journal that is directly upstream of this
remote journal.
Contains the null value if the journal receiver was
not attached to a remote journal.

SOURCE_JOURNAL_ASP_GROUP SRCASPGRP VARCHAR(10) The independent auxiliary storage pool (IASP)


Nullable group of the source journal.
Contains the null value if the journal receiver was
not attached to a remote journal.

SOURCE_JOURNAL_RECEIVER_LIBRARY SRCRCVLIB VARCHAR(10) The library name of the journal receiver that is
Nullable associated with the source journal.
Contains the null value if the journal receiver was
not attached to a remote journal.

REDIRECTED_RECEIVER_LIBRARY REDIR_LIB VARCHAR(10) The *TYPE1 receiver library redirection that was in
Nullable effect when this journal receiver was attached.
Contains the null value if the journal receiver
was not attached to a remote journal or
REMOTE_JOURNAL_TYPE is not *TYPE1.

FILTER_BY_OBJECT FTR_OBJECT VARCHAR(4) Specifies whether journal entries sent to the


Nullable remote journal will be filtered by object.

*NO Journal entries sent to the remote journal


will not be filtered by object.

*YES Journal entries deposited for objects that


indicated remote journal filtering at the
time they were deposited will not be sent
to the remote journal.

Contains the null value if the journal receiver was


not attached to a remote journal.

FILTER_IMAGES FTR_IMAGE VARCHAR(7) Specifies whether before images will be sent to the
Nullable remote journal.

*NONE All journal entries will be sent to


the remote journal, unless they are
filtered by the Filter by object or
Filter by program specifications.

*BEFORE Before images will not be sent to the


remote journal.

Contains the null value if the journal receiver was


not attached to a remote journal.

Database performance and query optimization 813


Table 194. JOURNAL_RECEIVER_INFO view (continued)

System Column Name


Column Name Data Type Description

FILTER_PROGRAMS FTR_PGM INTEGER The number of programs for which journal entries
Nullable sent on behalf of these programs were filtered
when sent to this journal receiver. These programs
are listed in the FILTER_PROGRAM_ARRAY and
FILTER_PROGRAM_JSON columns.
Contains the null value if the journal receiver was
not attached to a remote journal.

FILTER_PROGRAM_ARRAY FTR_ARRAY VARCHAR(219) An array of up to 20 names of 22 characters


Nullable apiece. The first 10 of each is a program name,
followed by a blank, followed by 10 characters for
the program library name. One comma separates
the entries. The program library name can be *ALL.
Journal entries sent on behalf of these programs
will not be sent to the remote journal.
Contains the null value if the journal receiver
was not attached to a remote journal or
FILTER_PROGRAMS is zero.

FILTER_PROGRAM_JSON FTR_LISTJ VARCHAR(498) CCSID A list of programs and libraries. Journal entries
1208 sent on behalf of these programs were filtered
Nullable when sent to this journal receiver. The program’s
library name may be *ALL.
This list is returned as an array within a JSON
object. Each entry in the JSON array contains two
JSON objects:
• An object with a name of "LIBRARY" and a value
of the library name containing the program
• An object with a name of "PROGRAM" and a
value of the program name
Contains the null value if the journal receiver
was not attached to a remote journal or
FILTER_PROGRAMS is zero.

Examples
• Return a list of journal receivers that have not been saved.

SELECT JOURNAL_RECEIVER_LIBRARY, JOURNAL_RECEIVER_NAME, STATUS


FROM QSYS2.JOURNAL_RECEIVER_INFO
WHERE STATUS = 'ONLINE';

• Return the length of time, in seconds, that journal receivers in RCVLIB were attached.

SELECT JOURNAL_RECEIVER_LIBRARY, JOURNAL_RECEIVER_NAME, TIMESTAMPDIFF(SECOND,


DETACH_TIMESTAMP, ATTACH_TIMESTAMP), SIZE
FROM QSYS2.JOURNAL_RECEIVER_INFO
WHERE DETACH_TIMESTAMP IS NOT NULL AND
JOURNAL_RECEIVER_LIBRARY = 'RCVLIB';

• Return a list of programs contained in the FILTER_PROGRAMS_JSON column related to journal receiver
RCV1 in RCVLIB.

SELECT j.*, r.*


FROM QSYS2.JOURNAL_RECEIVER_INFO r,
JSON_TABLE(FILTER_PROGRAM_JSON, 'lax $.PROGRAM_LIST'
COLUMNS(LIBRARY VARCHAR(10),
PROGRAM VARCHAR(10))) j
WHERE JOURNAL_RECEIVER_LIBRARY = 'RCVLIB' AND JOURNAL_RECEIVER_NAME = 'RCV1';

814 IBM i: Performance and Query Optimization


JOURNALED_OBJECTS view
The JOURNALED_OBJECTS view returns information about journaled objects. Only information about
external objects is returned. Internal objects such as commit blocks and access paths are not included.
The values returned for the columns in the view are closely related to the values returned by the
Retrieve Journal Information (QjoRetrieveJournalInformation) API and the Work with Journal Attributes
(WRKJRNA) CL command.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the journal, and
• *OBJOPR authority and some data authority other than *EXECUTE to the journal.
The following table describes the columns in the view. The system name is JRN_OBJS. The schema is
QSYS2.
Table 195. JOURNALED_OBJECTS view

Column Name System Column Name Data Type Description

JOURNAL_LIBRARY JRNLIB VARCHAR(10) The name of the library that contains the journal.

JOURNAL_NAME JRNNAME VARCHAR(10) The name of the journal.

IASP_NUMBER IASPNUMBER INTEGER The number of the auxiliary storage pool to which
storage for the journal is allocated.

IASP_NAME IASP_NAME VARCHAR(10) The device description name of the independent


auxiliary storage pool (IASP).
The special value of *SYSBAS indicates SYSBASE,
which includes the system ASP (ASP 1) and the
basic user ASPs (ASPs 2-32).

OBJECT_TYPE OBJ_TYPE VARCHAR(7) Type of object.

*DIR Directory

*DTAARA Data area

*DTAQ Data queue

*FILE Database file

*JRNRCV Journal receiver

*LIB Library

*STMF Stream file

*SYMLNK Symbolic link

OBJECT_LIBRARY OBJ_LIB VARCHAR(10) The name of the library that contains the object.
Nullable Contains the null value if OBJECT_TYPE is *DIR,
*STMF, or *SYMLNK.

OBJECT_NAME OBJ_NAME VARCHAR(10) The name of the object.

Nullable Contains the null value if OBJECT_TYPE is *DIR,


*STMF, or *SYMLNK.

FILE_TYPE FILE_TYPE VARCHAR(8) The type of file that is journaled.

Nullable LOGICAL Logical file

PHYSICAL Physical file

Contains the null value if OBJECT_TYPE is not


*FILE.

PATH_NAME PATH_NAME DBCLOB(16M) CCSID The path name of an integrated file system object.
1200
Contains the null value if OBJECT_TYPE is not
Nullable *DIR, *STMF, or *SYMLNK.

FILE_IDENTIFIER FILE_ID BINARY(16) The identifier associated with the integrated file
system object.
Nullable
Contains the null value if OBJECT_TYPE is not
*DIR, *STMF, or *SYMLNK.

Database performance and query optimization 815


Table 195. JOURNALED_OBJECTS view (continued)

Column Name System Column Name Data Type Description

JOURNAL_IMAGES IMAGES VARCHAR(6) Specifies the kinds of images written to the


journal for this object.
Nullable
*AFTER Only after images are written to the
journal.

*BOTH Both before and after images are


written to the journal.

Contains the null value if OBJECT_TYPE is


*JRNRCV.

OMIT_JOURNAL_ENTRY OMIT_ENTRY VARCHAR(10) Specifies the journal entries that are omitted.

Nullable *NONE No entries are omitted.

*OPNCLO Open and close entries are


omitted. Open and close
operations on the specified
file members do not create
open and close journal entries.
Using this option prevents the
use of TOJOBO and TOJOBC
entries on the Apply Journaled
Changes (APYJRNCHG) and
Remove Journaled Changes
(RMVJRNCHG) commands, but
it saves some storage space in
the attached receivers.

*OPNCLOSYN Open, close, and force entries


are omitted. Open, close,
and force operations on
the specified objects do
not generate open, close
and force journal entries.
Using this option prevents
the use of TOJOBO and
TOJOBC entries on the
Apply Journaled Changes
(APYJRNCHG) command, but it
saves some storage space in
the journal receivers.

Contains the null value if OBJECT_TYPE is


*JRNRCV.

INHERIT INHERIT VARCHAR(4) Specifies whether new objects created within this
journaled directory or library, moved into this
Nullable journaled directory or library, or restored into this
journaled directory or library should inherit the
journal state of the parent directory or library.

*NO New objects will not inherit the journal


state of the parent.

*YES New objects will inherit the journal state


of the parent.

Contains the null value if OBJECT_TYPE is not


*DIR or *LIB.

REMOTE_JOURNAL_FILTER RMT_FILTER VARCHAR(4) Specifies whether the journal entries deposited


for objects that inherit the journal state of the
Nullable directory or library are eligible for remote journal
filtering by object.

*NO Journal entries deposited for objects


will not be eligible for remote journal
filtering by object.

*YES Journal entries deposited for objects will


be eligible for remote journal filtering
by object. When using remote journal
filtering by object, journal entries for
the object will not be sent to the target
system.

Contains the null value if OBJECT_TYPE is


*JRNRCV.

816 IBM i: Performance and Query Optimization


Example
• Review all the objects journaled to APPLIB/APPJRN.

SELECT *
FROM QSYS2.JOURNALED_OBJECTS
WHERE OBJECT_LIBRARY = 'APPLIB' AND JOURNAL_NAME = 'APPJRN'
ORDER BY OBJECT_TYPE, OBJECT_LIBRARY, OBJECT_NAME, PATH_NAME;

MANAGE_AUDIT_JOURNAL_DATA_MART procedure
The MANAGE_AUDIT_JOURNAL_DATA_MART procedure populates a table with audit journal data for a
specific audit journal entry type from a specified time period, or deletes an existing data mart table.
The table is created in the specified library with the name AUDIT_JOURNAL_xx where xx corresponds to
the specified audit journal entry type. For example, when creating a data mart for the PW (Password) audit
journal entry, a table named AUDIT_JOURNAL_PW is created. The procedure uses “Audit journal entry
services” on page 658 to populate the table. The result of the call to the procedure, including any failure
message, is returned by the QSYS2.AUDIT_JOURNAL_DATA_MART_INFO view.
Authorization:
To call this procedure when data-mart-action is ADD, the caller must have:
• *AUDIT special authority
• *USE authority to the library that contains the audit journal data mart
• *OBJOPR and *ADD authority to the AUDIT_JOURNAL_xx table
• *USE and *OBJEXIST authority to the audit journal
• *USE authority to all requested journal receivers
To call this procedure when data-mart-action is CREATE, the caller must have:
• *AUDIT special authority.
• *OBJOPR, *READ, *ADD, and *EXECUTE authority to the library that contains the audit journal data mart
• *USE and *OBJEXIST authority to the audit journal
• *USE authority to all requested journal receivers
To call this procedure when data-mart-action is DROP, the caller must have:
• *AUDIT special authority
• *USE authority to the library that contains the audit journal data mart
• *OBJOPR and *OBJEXIST authority to the AUDIT_JOURNAL_xx table
To call this procedure when data-mart-action is REPLACE, the caller must have:
• *AUDIT special authority
• *OBJOPR, *READ, *ADD, and *EXECUTE authority to the library that will contain the audit journal data
mart
• *OBJOPR, *OBJMGT, *OBJEXIST, *ADD, and *DLT authority to the AUDIT_JOURNAL_xx table
• *USE and *OBJEXIST authority to the audit journal
• *USE authority to all requested journal receivers

Database performance and query optimization 817


MANAGE_AUDIT_JOURNAL_DATA_MART (

journal-entry-type
JOURNAL_ENTRY_TYPE =>

, data-mart-library
DATA_MART_LIBRARY =>

, starting-timestamp
STARTING_TIMESTAMP =>

, ending-timestamp
ENDING_TIMESTAMP =>

)
, data-mart-action
DATA_MART_ACTION =>

The schema is QSYS2.

journal- A character or graphic string expression that identifies the journal entry type to include
entry-type in the data mart. Only journal entry types that have corresponding “Audit journal entry
services” on page 658 are supported.
data-mart- A character or graphic string expression that identifies the library that contains the data
library mart table or where the data mart table is to be created.
data-mart-library must exist.
starting- A character or graphic string expression that identifies the starting timestamp to use.
timestamp If no timestamp is provided,
• *CONTINUE is used when data-mart-action is ADD.
• *FIRST is used when data-mart-action is CREATE or REPLACE.
• starting-timestamp will be ignored when data-mart-action is DROP.

*CONTINUE A timestamp just after the last value for ENTRY_TIMESTAMP in the
AUDIT_JOURNAL_xx table is used.
*FIRST The attach time for the oldest, attached journal receiver is used.

ending- A timestamp value that specifies the ending timestamp to use.


timestamp If no timestamp is provided,
• the current timestamp will be used when data-mart-action is ADD, CREATE, or
REPLACE.
• ending-timestamp will be ignored when data-mart-action is DROP.

data-mart- A character or graphic string expression that indicates the type of action to perform. If no
action string is provided, CREATE is used.

ADD Inserts data into an existing data mart table and adds an
entry for this data-mart-library and journal-entry-type to the
AUDIT_JOURNAL_DATA_MART_INFO table.
If the table does not exist, an error is returned.

818 IBM i: Performance and Query Optimization


CREATE Creates and populates a new data mart table and adds an
entry for this data-mart-library and journal-entry-type to the
AUDIT_JOURNAL_DATA_MART_INFO table.
If the table exists, an error is returned.
DROP Deletes the data mart table and removes the corresponding entry from the
AUDIT_JOURNAL_DATA_MART_INFO table.
If the table does not exist, an error is returned. If there is an entry in the
AUDIT_JOURNAL_DATA_MART_INFO table, it is removed.
REPLACE Creates and populates a new data mart table and adds an
entry for this data-mart-library and journal-entry-type to the
AUDIT_JOURNAL_DATA_MART_INFO table.
If the table exists, the current rows will be deleted.
If the table does not exist, it is created.

Notes
The resulting AUDIT_JOURNAL_xx table will have the same format as the corresponding “Audit journal
entry services” on page 658 table function. The table is owned by the caller who first creates the table
and *PUBLIC is configured with *EXCLUDE authority. The system name of the table is AJ_xx. The table is
not managed by the system. It is up to the user to grant access to other users and to maintain the table.
To view an AUDIT_JOURNAL_xx table, the caller must have:
• *USE authority to the library that contains the AUDIT_JOURNAL_xx table.
• *OBJOPR and *READ authority to the AUDIT_JOURNAL_xx table.

Examples
• Build a data mart for PW audit journal entries from the last month in the DMARTLIB library.

CALL QSYS2.MANAGE_AUDIT_JOURNAL_DATA_MART(JOURNAL_ENTRY_TYPE => 'PW',


DATA_MART_LIBRARY => 'DMARTLIB',
STARTING_TIMESTAMP => CURRENT DATE - 1 MONTH,
ENDING_TIMESTAMP => CURRENT TIMESTAMP);

• Add journal data for PW entries to the existing data mart in DMARTLIB.

CALL QSYS2.MANAGE_AUDIT_JOURNAL_DATA_MART(JOURNAL_ENTRY_TYPE => 'PW',


DATA_MART_LIBRARY => 'DMARTLIB',
STARTING_TIMESTAMP => '*CONTINUE',
ENDING_TIMESTAMP => CURRENT TIMESTAMP,
DATA_MART_ACTION => 'ADD'
);

• Drop the DMARTLIB.AUDIT_JOURNAL_PW table.

CALL QSYS2.MANAGE_AUDIT_JOURNAL_DATA_MART(JOURNAL_ENTRY_TYPE => 'PW',


DATA_MART_LIBRARY => 'DMARTLIB',
DATA_MART_ACTION => 'DROP'
);

REMOTE_JOURNAL_INFO view
The REMOTE_JOURNAL_INFO view returns information about every remote journal defined for a local or
remote journal on the IBM i where this view is referenced. The remote journals returned by this service
exist on a different IBM i, as noted by the remote database (RDB) name.
This information is similar to what is returned by the Retrieve Journal Information
(QjoRetrieveJournalInformation) API.

Database performance and query optimization 819


Authorization: The caller must have:
• *EXECUTE authority to the library containing the journal, and
• *OBJOPR authority and some data authority other than *EXECUTE to the journal.
The following table describes the columns in the view. The system name is RMT_JRNS. The schema is
QSYS2.
Table 196. REMOTE_JOURNAL_INFO view

Column Name System Column Name Data Type Description

SOURCE_JOURNAL_LIBRARY SRC_JRNLIB VARCHAR(10) The library that contains SOURCE_JOURNAL.

SOURCE_JOURNAL SRC_JRN VARCHAR(10) The name of the journal that has the remote
journal defined.

REMOTE_DATABASE_NAME RMT_RDB VARCHAR(18) The name of the remote database that is the
target and contains the remote journal.

REMOTE_JOURNAL_LIBRARY RMT_JRNLIB VARCHAR(10) The library that contains REMOTE_JOURNAL.

REMOTE_JOURNAL RMT_JRN VARCHAR(10) The name of the remote journal that is the target
for remote journaling.

REMOTE_JOURNAL_RECEIVER_LIBRARY RMT_RCVLIB VARCHAR(10) The library name of the remote journal receiver
that is the target for remote journaling.
The special value of *SRCRCVLIB indicates the
journal receivers are created on the target system
in the same library as they exist on the source
system.

REMOTE_JOURNAL_STATE RMT_STATE VARCHAR(8) The state of the remote journaling.

ACTIVE The remote journal is ready to


receive any journal entries from its
source journal.

CTLINACT The remote journal is in the


process of a controlled inactivate.
Therefore, the remote journal
will be receiving those journal
entries that were already queued
for replication when the Change
Remote Journal (CHGRMTJRN)
command or the Change Journal
State (QjoChangeJournalState) API
requested to inactivate the remote
journal. However, no entries
deposited after that request will be
replicated to the remote journal.

FAILED The remote journal is not ready


to receive any journal entries
from its source journal due to
a remote journal function failure,
for example, a communications
failure. You will need to inactivate
the remote journal by using
the Change Remote Journal
(CHGRMTJRN) command or by
calling the Change Journal State
(QjoChangeJournalState) API.

INACTIVE The remote journal is not ready to


receive any journal entries from its
source journal.

PENDING The remote journal is transitioning


from an INACTIVE state to an
ACTIVE state.

REMOTE_JOURNAL_TYPE RMT_JTYPE VARCHAR(6) The type of remote journal that was created.
The type influences characteristics of the remote
journal such as journal receiver restore options,
redirection capabilities, and remote journal
association support.

*TYPE1 Type 1 remote journal

*TYPE2 Type 2 remote journal

820 IBM i: Performance and Query Optimization


Table 196. REMOTE_JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

DELIVERY_MODE DELIVERY VARCHAR(10) The remote journal delivery mode that is being
used to replicate journal entries to the remote
Nullable journal.

*ASYNC Journal entries are being


delivered or replicated
asynchronously.

*ASYNCPEND Journal entries are to


be delivered or replicated
asynchronously, but the remote
journal is currently in catch-up
mode.

*SYNC Journal entries are being


delivered or replicated
synchronously.

*SYNCPEND Journal entries are to


be delivered or replicated
synchronously, but the remote
journal is currently in catch-up
mode.

Contains the null value if


REMOTE_JOURNAL_STATE is not ACTIVE or
CTLINACT.

DATA_PORT_SERVICES_NODE_ID NODE_ID VARCHAR(8) The node identifier being used by data port
services to identify the target system in a cluster
Nullable environment. If a node identifier and at least
one internet address is retrieved, then data
port services is being used as an alternate
communication method to the target system.
Contains the null value if the remote journal is not
configured for data port services.

DATA_PORT_SERVICES_ADDRESS_1 IP_ADDR1 VARCHAR(45) The first internet address being used by data port
services to communicate to the target system.
Nullable
Contains the null value if the remote journal is not
configured for data port services.

DATA_PORT_SERVICES_ADDRESS_2 IP_ADDR2 VARCHAR(45) The second internet address being used by


data port services to communicate to the target
Nullable system.
Contains the null value if the remote journal is not
configured for data port services or there are less
than two internet addresses being used.

DATA_PORT_SERVICES_ADDRESS_3 IP_ADDR3 VARCHAR(45) The third internet address being used by data port
services to communicate to the target system.
Nullable
Contains the null value if the remote journal is not
configured for data port services or there are less
than three internet addresses being used.

DATA_PORT_SERVICES_ADDRESS_4 IP_ADDR4 VARCHAR(45) The fourth internet address being used by data
port services to communicate to the target
Nullable system.
Contains the null value if the remote journal is not
configured for data port services or there are less
than four internet addresses being used.

Database performance and query optimization 821


Table 196. REMOTE_JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

VALIDITY_CHECKING VALID_CHK VARCHAR(9) The validity checking status. When


communications validity checking is turned
Nullable on, the remote journal environment provides
additional checking to verify that the data which
is received by the target system matches the data
that was sent from the source system. If the data
does not match, the data will not be written to the
target system, the remote journal environment
will be inactivated, and messages indicating the
communications failure will be issued to the
journal message queue and QHST.

*DISABLED Communications validity


checking is turned off for this
remote journal environment.

*ENABLED Communications validity


checking is turned on for this
remote journal environment.

Contains the null value if


REMOTE_JOURNAL_STATE is not ACTIVE or
CTLINACT.

SENDING_TASK_PRIORITY PRIORITY INTEGER The priority of the sending task on the source
system.
Nullable
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE or
DELIVERY_MODE is not *ASYNC or *ASYNCPEND.

SYNCHRONOUS_SENDING_TIME_OUT TIME_OUT INTEGER The maximum amount of time, in seconds, to


wait for a response from the remote system when
Nullable a response is required in a synchronous remote
journal environment.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE or
DELIVERY_MODE is not *SYNC or *SYNCPEND.

MAXIMUM_RESTART_ATTEMPTS MAXRESTART INTEGER The number of times the operating system will
attempt to reactivate the remote journal after a
Nullable recoverable failure.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE.

RESTART_DELAY_TIME RESTARTDLY INTEGER The number of seconds between attempts to


reactivate the remote journal after a recoverable
Nullable failure.
Contains the null value if
MAXIMUM_RESTART_ATTEMPTS is null or 0.

FILTER_BY_OBJECT FTR_OBJECT VARCHAR(4) Specifies whether journal entries sent to the


remote journal will be filtered by object.
Nullable
*NO Journal entries sent to the remote
journal will not be filtered by object.

*YES Journal entries deposited for objects


that indicated remote journal filtering at
the time they were deposited will not be
sent to the remote journal.

Contains the null value if


REMOTE_JOURNAL_STATE is INACTIVE.

FILTER_IMAGES FTR_IMAGE VARCHAR(7) Specifies whether before images will be sent to


the remote journal.
Nullable
*NONE All journal entries will be sent to
the remote journal, unless they are
filtered by the Filter by object or
Filter by program specifications.

*BEFORE Before images will not be sent to


the remote journal.

Contains the null value if


REMOTE_JOURNAL_STATE is INACTIVE.

822 IBM i: Performance and Query Optimization


Table 196. REMOTE_JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

FILTER_PROGRAMS FTR_PGM INTEGER The number of programs returned in


FILTER_PROGRAM_ARRAY. Journal entries sent
Nullable on behalf of these programs will not be sent to
the remote journal.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE.

FILTER_PROGRAM_ARRAY FTR_ARRAY VARCHAR(219) An array of up to 20 names of 22 characters each.


The first 10 of each is a program name, followed
Nullable by a blank, followed by 10 characters for the
program library name. One comma separates the
entries. The program library name can be *ALL.
Journal entries sent on behalf of these programs
will not be sent to the remote journal.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE or
FILTER_PROGRAMS is zero.

FILTER_PROGRAM_JSON FTR_LISTJ VARCHAR(498) CCSID A list of programs and libraries. Journal entries
1208 sent on behalf of these programs were filtered
Nullable when sent to this journal receiver. The program’s
library name may be *ALL.
This list is returned as an array within a JSON
object. Each entry in the JSON array contains two
JSON objects:
• An object with a name of "LIBRARY" and
a value of the library name containing the
program
• An object with a name of "PROGRAM" and a
value of the program name
Contains the null value if the journal receiver
was not attached to a remote journal or
FILTER_PROGRAMS is zero.

BUNDLES_SENT BUNDLES BIGINT The number of bundles that have been sent
to the target system since the source journal
Nullable transitioned to an active state.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE.

MAXIMUM_BUNDLE_SIZE BUNDLE_SIZ BIGINT The number of bytes in the largest bundle that
has been sent to the target system since the
Nullable source journal transitioned to an active state.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE.

MAXIMUM_BUNDLE_SIZE_TIME BUNDLE_TIM TIMESTAMP The date and time that the maximum bundle size
was sent to the target system.
Nullable
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE or
MAXIMUM_BUNDLE_SIZE is 0.

SUPER_BUNDLE_MODE_COUNT SUPER_CNT BIGINT The number of times that the remote journal
environment has automatically gone into super
Nullable bundling mode. Super bundling mode helps the
remote journal environment keep up with the
local journal when the local journal has a high rate
of journal entry deposits.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE or
DELIVERY_MODE is not *ASYNC or *ASYNCPEND.

ENTRIES_BEHIND BEHIND BIGINT The number of entries that are waiting to be sent
to the target system.
Nullable
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE or
DELIVERY_MODE is not *ASYNC or *ASYNCPEND.

Database performance and query optimization 823


Table 196. REMOTE_JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

MAXIMUM_ENTRIES_BEHIND MBEHIND BIGINT The maximum number of entries that were


waiting to be sent to the target system since the
Nullable source journal transitioned to an active state.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE or
DELIVERY_MODE is not *ASYNC or *ASYNCPEND.

MAXIMUM_ENTRIES_BEHIND_TIME MBEHINDT TIMESTAMP The date and time that


MAXIMUM_ENTRIES_BEHIND occurred.
Nullable
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE or
DELIVERY_MODE is not *ASYNC or *ASYNCPEND
or MAXIMUM_ENTRIES_BEHIND is 0.

TIME_BEHIND TBEHIND BIGINT The value, in hundredths of seconds, that the


source journal is behind in sending journal entries
Nullable to the target system.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE or
DELIVERY_MODE is not *ASYNC or *ASYNCPEND.

MAXIMUM_TIME_BEHIND MTBEHIND BIGINT The maximum value, in hundredths of seconds,


that the source journal was behind in sending
Nullable journal entries to the target system.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE or
DELIVERY_MODE is not *ASYNC or *ASYNCPEND.

MAXIMUM_TIME_BEHIND_TIME MTBEHINDT TIMESTAMP The date and time that MAXIMUM_TIME_BEHIND


occurred.
Nullable
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE or
DELIVERY_MODE is not *ASYNC or *ASYNCPEND
or MAXIMUM_TIME_BEHIND is 0.

RETRANSMISSIONS RETRANS BIGINT The total number of times the local


system retransmitted a segment because an
Nullable acknowledgement was not received. This is a
cumulative count of all segments resent since
the remote journal was last activated. A value
greater than zero may indicate a problem with the
network.
Contains the null value if this information is not
available

LAST_CATCHUP_TIME LAST_CATCH TIMESTAMP The date and time that the remote journal
environment last transitioned to DELIVERY_MODE
Nullable *ASYNCPEND or *SYNCPEND.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE.

LAST_ACTIVE_TIME LAST_ACT TIMESTAMP The date and time that the remote
journal environment last transitioned from
Nullable DELIVERY_MODE *ASYNCPEND or *SYNCPEND to
DELIVERY_MODE *ASYNC or *SYNC.
Contains the null value if
REMOTE_JOURNAL_STATE is INACTIVE

CONTROLLED_INACTIVATE_SEQUENCE_ INACT_SEQ DECIMAL(21,0) The sequence number of the last journal entry
NUMBER that was queued for replication before the Change
Nullable Remote Journal (CHGRMTJRN) command or the
Change Journal State (QjoChangeJournalState)
API was called to start a controlled inactivate of
the remote journal.
Contains the null value if
REMOTE_JOURNAL_STATE is not CTLINACT.

CONTROLLED_INACTIVATE_JOURNAL_ INACTJRCVL VARCHAR(10) The library of the journal receiver that contains
RECEIVER_LIBRARY the
Nullable CONTROLLED_INACTIVATE_SEQUENCE_NUMBE
R.
Contains the null value if
REMOTE_JOURNAL_STATE is not CTLINACT.

824 IBM i: Performance and Query Optimization


Table 196. REMOTE_JOURNAL_INFO view (continued)

Column Name System Column Name Data Type Description

CONTROLLED_INACTIVATE_JOURNAL_ INACTJRCV VARCHAR(10) The name of the journal receiver that contains the
RECEIVER CONTROLLED_INACTIVATE_SEQUENCE_NUMBE
Nullable R.
Contains the null value if
REMOTE_JOURNAL_STATE is not CTLINACT.

SOURCE_JOURNAL_IASP_NUMBER SRC_ASPNUM INTEGER The number of the auxiliary storage pool to which
storage for the journal that has the remote journal
defined is allocated.

SOURCE_JOURNAL_IASP_NAME SRC_ASPNAM VARCHAR(10) The device description name of the independent


auxiliary storage pool (IASP).
The special value of *SYSBAS indicates SYSBASE,
which includes the system ASP (ASP 1) and the
basic user ASPs (ASPs 2-32).

Example
• Return information about remote journals defined for system RMTSYS1.

SELECT * FROM QSYS2.REMOTE_JOURNAL_INFO


WHERE REMOTE_DATABASE_NAME = 'RMTSYS1';

SMAPP_ACCESS_PATHS view
The SMAPP_ACCESS_PATHS view returns a list of access paths which are monitored by System-Managed
Access Path Protection (SMAPP).
Some access paths are ineligible for SMAPP protection. See How the system chooses access paths to
protect for more details.
Authorization: The caller must have *JOBCTL special authority.
The following table describes the columns in the view. The system name is SMAPP_AP. The schema is
QSYS2.
Table 197. SMAPP_ACCESS_PATHS view

Column Name System Column Name Data Type Description

SYSTEM_TABLE_SCHEMA LIB_NAME VARCHAR(10) The library containing the database file associated
with the access path.

SYSTEM_TABLE_NAME FILE_NAME VARCHAR(10) The database file associated with the access path.

ASP_NUMBER ASPNUMBER INTEGER The number of the auxiliary storage pool containing
the access path.

IASP_NAME IASP_NAME VARCHAR(10) The name of the auxiliary storage pool containing
the access path. The special value of *SYSBAS is
returned if ASP_NUMBER is not greater than or equal
to 33.

Database performance and query optimization 825


Table 197. SMAPP_ACCESS_PATHS view (continued)

Column Name System Column Name Data Type Description

STATUS STATUS VARCHAR(11) The eligibility and protection status of the access
path.

INELIGIBLE This access path is not eligible


to be protected by the system
and may need to be rebuilt
during an initial program load
(IPL) or during the vary on of
an independent ASP after an
abnormal system end.

PROTECTED This access path is protected by


the system.

UNPROTECTED This access path is not protected


by the system and may need
to be rebuilt during an initial
program load (IPL) or during the
vary on of an independent ASP
after an abnormal system end.

INELIGIBLE_REASON INELIG_RSN VARCHAR(17) The reason that the access path is not eligible for
access protection.
Nullable
MULTIPLE The access path is built over
JOURNALS physical files which are journaled
to separate journals.

JOURNAL The access path is built over a


STANDBY physical file which is journaled to
a journal whose journal state is
currently *STANDBY.

Contains the null value if STATUS is not *INELIGIBLE.

ESTIMATED_RECOVERY EST_RECOV BIGINT The estimated amount of time, in seconds, that the
system would take to recover the access path during
an initial program load (IPL) or during the vary on of
an independent ASP after an abnormal system end if
the access path is not chosen for protection.

Example
• List all the access paths in APPLIB that are not currently protected.

SELECT * FROM QSYS2.SMAPP_ACCESS_PATHS


WHERE LIB_NAME = 'APPLIB' AND STATUS <> 'PROTECTED'
ORDER BY ESTIMATED_RECOVERY DESC;

Librarian Services
These services provide object and library list information.

JOURNAL_INHERIT_RULES view
The JOURNAL_INHERIT_RULES view returns the journal inherit rules for libraries.
The rules define which objects created in a library, moved into a library, or restored into a library should
inherit the journal state of the library and the inherited journal attributes.
Each rule defines object types, object names, and operations that the rule applies to. Multiple rules can
be defined for the same set of objects. If multiple rules are defined for the same object and operation, the
last rule defined for that object will be applied.
This information is similar to the journal inherit rules returned by the Retrieve Library Description
(QLIRLIBD) API.
Authorization: The caller must have *READ authority to the library.

826 IBM i: Performance and Query Optimization


The following table describes the columns in the view. The system name is LIB_JRN. The schema is
QSYS2.
Table 198. JOURNAL_INHERIT_RULES view

Column Name System Column Name Data Type Description

LIBRARY_NAME LIBRARY VARCHAR(10) The name of the library for this rule.

JOURNALED JOURNALED VARCHAR(3) The current journaling status of the library. Rules are only in
effect when the library is journaled.

NO The library is not currently journaled.

YES The library is currently journaled.

IASP_NUMBER IASPNUMBER INTEGER The number of the auxiliary storage pool (ASP) from which
the system allocates storage for the library.

IASP_NAME IASP_NAME VARCHAR(10) The device description name of the independent auxiliary
storage pool (IASP).
The special value of *SYSBAS indicates SYSBASE, which
includes the system ASP (ASP 1) and the basic user ASPs
(ASPs 2-32).

ORDINAL_POSITION ORDINAL INTEGER The order this rule was added for this library. The number
starts at one for each library and increments by one for
every additional rule for that library. If more than one rule
is defined for any object, the one with the higher number will
be used.

OBJECT_TYPE TYPE VARCHAR(7) Specifies the object type of the objects that are identified by
this rule.

*ALL This rule applies to all object types that can be


journaled.

*DTAARA This rule applies to data areas.

*DTAQ This rule applies to data queues.

*FILE This rule applies to database physical files.

Database performance and query optimization 827


Table 198. JOURNAL_INHERIT_RULES view (continued)

Column Name System Column Name Data Type Description

OPERATION OPERATION VARCHAR(10) The operations performed on the object type for which
journaling is to be started if other criteria specified for the
object type are also satisfied.

*ALLOPR Journaling is started for all objects created


in, moved into, or restored into the
library. This is a combination of the values
*CREATE, *MOVE, and *RESTORE.

*CREATE Journaling is started for all objects created


in the library.

*MOVE Journaling is started for all objects moved


into the library if they are not already
journaled.

*RESTORE If an object is restored over a currently


existing object, the restored object will
retain the same journal options and journal
state of the object it was restored over. If
an object was never journaled when it was
saved, journaling is started for the object
when it is restored into the library. If an
object was journaled when it was saved,
it will first attempt to start journaling to
the journal it was journaled to when it was
saved, with the same journal options it had
when it was saved. If that journal does
not exist, the object will start journaling
to the same journal the library is journaled
to, with the journal options defined by this
rule.

*RSTOVRJRN If an object is restored over a currently


existing object, the restored object will
retain the same journal options and journal
state of the object it was restored over.
Otherwise, journaling is started for all
objects restored into the library, regardless
of the journal options and journal state of
the object when it was saved.

RULE_ACTION ACTION VARCHAR(8) Indicates whether the objects that match the object type and
operation in this rule will be included or omitted from the list
of objects that inherit the journal options and journal state of
the library.

*INCLUDE All objects that match the object type and


operation of this rule will inherit the journal
options and journal state of the library.

*OMIT All objects that match the object type and


operation of this rule will not inherit any
journaling attributes or state from the library.
This overrides a *INCLUDE rule and therefore
can be used to omit a subset of a previously
defined *INCLUDE rule.

NAME_FILTER NAMEFILTER VARCHAR(10) The object names of the objects that are identified by this
rule.
Nullable
name This rule applies to all objects that match the
other criteria and match the specified name.

generic- This rule applies to all objects that match the


name other criteria and match the specified generic
name.
A generic name is specified as a string that
contains one or more characters followed by
an asterisk (*). If a generic name is specified,
then all objects that have names with the
same prefix as the generic object name are
selected.

*ALL This rule applies to all objects that match the


other criteria.

828 IBM i: Performance and Query Optimization


Table 198. JOURNAL_INHERIT_RULES view (continued)

Column Name System Column Name Data Type Description

JOURNAL_IMAGES IMAGES VARCHAR(7) The kinds of journal images that are written to the journal
receiver for changes to objects that inherit the journal
Nullable options and journal state from the library.

*AFTER Only after images are journaled for an object


for which journaling is started because it
inherits the journaling attributes from the
library.

*BOTH Both before and after images are journaled


for an object for which journaling is started
because it inherits the journal option from the
library. This value is only valid for data area
(*DTAARA) and database file (*FILE) objects.
If this value is specified and *ALL is specified
for object type, the system will generate
both before and after images for data areas
and database files and the system will only
generate after images for all other object types.

*OBJDFT The default value for each object type will be


used for this journal option when an object
inherits the journaling attributes from the
library. Database files (*FILE) will have both
before and after images generated by the
system. All other object types will have only
after images generated by the system.

Contains the null value if RULE_ACTION is *OMIT.

OMIT_JOURNAL_ENTRY OMIT_ENTRY VARCHAR(7) The journal entries that are not to be written for changes to
objects that inherit the journaling options and state of the
Nullable library.

*NONE No journal entries will be omitted for objects


that inherit the journal options and journal
state from the library.

*OBJDFT The default value for each object type will be


used for this journal option when an object
inherits the journal options and journal state
from the library. Open and close entries will
be omitted for database files (*FILE). No other
object types will omit journal entries.

*OPNCLO Open and close entries are omitted for


database file (*FILE) objects that inherit the
journal options and journal state from the
library.
This prevents the use of TOJOBO and TOJOBC
entries on the Apply Journaled Changes
(APYJRNCHG) and Remove Journaled Changes
(RMVJRNCHG) commands, but it saves some
storage space in the journal receivers.
This value is only valid for object type *FILE. If
this value is specified and *ALL is specified for
object type, database files will omit the entries.
All other object types will not omit any journal
entries.

Contains the null value if RULE_ACTION is *OMIT.

Database performance and query optimization 829


Table 198. JOURNAL_INHERIT_RULES view (continued)

Column Name System Column Name Data Type Description

REMOTE_JOURNAL_FILTER RMT_FILTER VARCHAR(7) Specifies whether the journal entries written for the objects
that inherit the journal state of the library should be eligible
Nullable for remote journal filtering by object.

*NO Journal entries deposited for the objects that


inherit the journal state of the library will not be
eligible for remote journal filtering by object.

*OBJDFT The default value for each object type will


be used for this journaling attribute when an
object inherits the journal state of the library.
For all object types, journal entries deposited
for the objects that inherit the journal state of
the library will not be eligible for remote journal
filtering by object.

*YES Journal entries deposited for the objects that


inherit the journal state of the library will be
eligible for remote journal filtering by object.
When using remote journal filtering by object,
most journal entries for the object will not be
sent to the target system.

Example
• Retrieve the journal inherit rules for library APPLIB.

SELECT * FROM QSYS2.JOURNAL_INHERIT_RULES


WHERE LIBRARY_NAME = 'APPLIB';

LIBRARY_INFO table function


The LIBRARY_INFO table function returns a result table that contains information about a specific library.
This information is similar to what is returned by the Retrieve Library Description (QLIRLIBD) API and the
Retrieve Library Description (RTVLIBD) command
Authorization: The caller must have *READ authority to the library. The null value is returned for the
OBJECT_AUDIT_CREATE column unless the caller has *ALLOBJ or *AUDIT special authority.

LIBRARY_INFO ( library-name
LIBRARY_NAME =>

, ignore-errors
IGNORE_ERRORS =>

)
, detailed-info
DETAILED_INFO =>

The schema is QSYS2.

library-name An expression that contains the name of a library.


ignore-errors A character or graphic string expression that identifies what to do when an error is
encountered.

NO An error is returned.
YES A warning is returned.
No row is returned when an error is encountered. This is the default.

830 IBM i: Performance and Query Optimization


detailed-info A character or graphic string expression that indicates which columns should be returned.

LIBRARY_SIZE All the columns including the LIBRARY_SIZE column are returned. For
a library with a large number of objects, LIBRARY_SIZE can be a time
consuming calculation. This is the default.
NO Null is returned for the LIBRARY_SIZE column.

The result of the function is a table containing one row with the format shown in the following table. All
the columns are nullable.
Table 199. LIBRARY_INFO table function

Column Name Data Type Description

OBJECT_COUNT INTEGER The total number of external objects in the specified library. The count
includes objects to which you may not be authorized.

LIBRARY_SIZE BIGINT The size of the library, in bytes, which includes the size of the objects in the
library plus the size of the library object itself. This value will be a rounded
value for a library larger than 1 000 000 000 bytes.
Contains the null value if detailed-info is NO.

LIBRARY_SIZE_COMPLETE VARCHAR(3) Whether LIBRARY_SIZE includes all objects in the library.

NO Some objects in the library were omitted because they were locked,
or the user does not have any authority to the object.

YES The size of all the objects in the library was used in determining the
total library size.

Contains the null value if detailed-info is NO.

LIBRARY_TYPE CHAR(4) The library type.

PROD The library is a production library. Database files in production


libraries cannot be opened for updating if a user, while in debug
mode, requested that production libraries be protected.

TEST The library is a test library. All objects in a test library can be
updated during a test. See the Start Debug (STRDBG) command in
the on-line help for more details.

TEXT_DESCRIPTION VARCHAR(50) The user-defined text that briefly describes the library and its function.
Contains the null value if the library has no descriptive text.

IASP_NAME VARCHAR(10) The auxiliary storage pool (ASP) device name where the library is stored.
If the library is in the system ASP or one of the basic user ASPs, contains
*SYSBAS.
Contains the null value if the name of the ASP device cannot be determined.

IASP_NUMBER INTEGER The number of the auxiliary storage pool (ASP) from which the system
allocates storage for the library.

Database performance and query optimization 831


Table 199. LIBRARY_INFO table function (continued)

Column Name Data Type Description

CREATE_AUTHORITY VARCHAR(10) The default public authority for an object created into the library. This is
the authority given to a user who does not have specific authority to the
object, who is not on an authorization list specified for the object, and
whose user groups have no specific authority to the object. When you create
an object into the library, the AUT parameter on the create command for the
object determines the public authority for the object. If the AUT value on
the create command for the object is *LIBCRTAUT, which is the default, the
public authority for the object is set to the CRTAUT value for the library.

*ALL The user can perform all authorized operations on an


object created in this library.

*CHANGE The user can read the object description and has
read, add, update, and delete authority to an object
created in this library.

*EXCLUDE The user is prevented from accessing an object


created in this library.

*SYSVAL The default authority for an object created in this


library is determined by the value specified by the
QCRTAUT system value.

*USE The user can read the object and its description but
cannot change them for an object created in this
library.

Authorization list The name of the authorization list that secures an


name object created in this library. The default public
authority is taken from the authorization list, and the
public authority for the object is specified as *AUTL.

OBJECT_AUDIT_CREATE VARCHAR(7) The auditing value for objects created in this library.

*ALL All change or read access to the object is logged.

*CHANGE All change access to the object by all users is logged.

*NONE Use or change access to the object is not logged (no audit
entry is sent to the security journal).

*SYSVAL The value specified in the system value QCRTOBJAUD is


used.

*USRPRF The user profile of the user who accesses the object
is used to determine if an audit record is sent for this
access. The OBJAUD parameter of the Change User Auditing
(CHGUSRAUD) command is used to turn auditing on for a
specific user.

Contains the null value if caller does not have either all object (*ALLOBJ) or
audit (*AUDIT) special authority.

JOURNALED VARCHAR(3) Identifies the current journaling status of the library.

NO The library is not currently journaled.

YES The library is currently journaled.

JOURNAL_LIBRARY VARCHAR(10) The name of the library that contains the journal that receives the journaled
changes to the library, if the library is currently journaled. If the library was
previously journaled but is not currently journaled, contains the name of the
library that contains the last journal to which the library was journaled.
Contains the null value if journaling has never been started for this library.

JOURNAL_NAME VARCHAR(10) The name of the journal that receives the journaled changes to the library, if
the library is currently journaled. If the library was previously journaled but
is not currently journaled, contains the name of the last journal to which the
library was journaled.
Contains the null value if journaling has never been started for this library.

832 IBM i: Performance and Query Optimization


Table 199. LIBRARY_INFO table function (continued)

Column Name Data Type Description

INHERIT_JOURNALING VARCHAR(3) Identifies whether new journal-eligible objects created into, moved into, or
restored into this library should inherit journaling from the library according
to the journal inherit rules.

NO The new journal-eligible objects will not inherit journaling from the
library.

YES The new journal-eligible objects will inherit journaling from the
library according to the journal inherit rules.

JOURNAL_INHERIT_RULES INTEGER The number of inherit rules defined for this library. The rules can be listed
using the QSYS2.JOURNAL_INHERIT_RULES view.

JOURNAL_START_TIMESTAMP TIMESTAMP The timestamp journaling was last started for this library.
Contains the null value if journaling has never been started for this library.

APPLY_STARTING_RECEIVER_LIBRARY VARCHAR(10) Specifies the library name of the oldest journal receiver needed to
successfully use the Apply Journaled Changes (APYJRNCHG) command.
Contains the null value if the object has not been journaled or it has not
been saved and restored since journaling was started.

APPLY_STARTING_RECEIVER VARCHAR(10) Specifies the name of the oldest journal receiver needed to successfully use
the Apply Journaled Changes (APYJRNCHG) command.
Contains the null value if the object has not been journaled or it has not
been saved and restored since journaling was started.

APPLY_STARTING_RECEIVER_ASP VARCHAR(10) The auxiliary storage pool (ASP) device name where
APPLY_STARTING_RECEIVER is stored. If APPLY_STARTING_RECEIVER is
in the system ASP or one of the basic user ASPs, contains *SYSBAS.
Contains the null value if the name of the ASP device cannot be determined.

Example
• Retrieve information about library APPLIB.

SELECT * FROM TABLE(QSYS2.LIBRARY_INFO('APPLIB'));

LIBRARY_LIST_INFO view
The LIBRARY_LIST_INFO view contains information about the current job's library list.
The information returned is similar to the detail available through the DSPLIBL (Display Library List) CL
command.
Authorization: None required.
The following table describes the columns in the view. The system name is LIBLIST. The schema is
QSYS2.
Table 200. LIBRARY_LIST_INFO view

Column Name System Column Name Data Type Description

ORDINAL_POSITION COLNO INTEGER Position of this entry in the library list.

SCHEMA_NAME NAME VARCHAR(128) Name of the schema.

Nullable

SYSTEM_SCHEMA_NAME SYS_NAME VARCHAR(10) System name of the schema.

Database performance and query optimization 833


Table 200. LIBRARY_LIST_INFO view (continued)

Column Name System Column Name Data Type Description

TYPE TYPE VARCHAR(15) The portion of the library list containing the
selected library. Possible values are:

USER The library is in the user portion of


the library list.

SYSTEM The library is in the system portion


of the library list.

PRODUCT The library is a product library in the


library list.

CURRENT The library is the current library


entry in the library list.

IASP_NUMBER IASP SMALLINT The number of the auxiliary storage pool where
storage is allocated for the library.
Nullable

TEXT_DESCRIPTION TEXT VARGRAPHIC(50) CCSID The text description of the library.


1200
Contains the null value is there is no text
Nullable description.

Example
• See the current library list for your job

SELECT * FROM QSYS2.LIBRARY_LIST_INFO

OBJECT_STATISTICS table function


The OBJECT_STATISTICS table function returns information about objects in a library.
Authorization:
• For an object that is not a user profile:
– If the caller has *EXECUTE authority to the library,
- If the caller has *OBJOPR and *READ authority to an object, full details are returned.
- Otherwise, partial information is returned along with an SQL warning of '01548'.
Otherwise, the object information is not returned.
• For a user profile object:
– The caller must have at least one of the following:
- Some authority to the user profile, or
- Authorization to the QIBM_DB_SECADM function usage identifier.
Otherwise, the user profile object information is not returned.
The caller must have *ALLOBJ or *AUDIT special authority to return values for the OBJECT_AUDIT
column.

834 IBM i: Performance and Query Optimization


OBJECT_STATISTICS ( object-schema ,
OBJECT_SCHEMA =>

object-type-list
OBJTYPELIST =>

)
, object-name
OBJECT_NAME =>

The schema is QSYS2.

object- A character or graphic string expression that identifies the name of a library. If the library's
schema name is a delimited name, the delimited form of the name must be specified. It can be either
a long or short library name.
The following special values are allowed for object-schema.

*ALL All libraries.


*ALLAVL All libraries in all available ASPs.
*ALLUSR All user libraries in *SYSBAS and the current thread's ASP group.
*ALLUSRAVL All user libraries in all available ASPs.
*CURLIB The job's current library.
*LIBL The library list.
*USRLIBL The job's current library and the user portion of the library list.

The following special value is allowed for object-schema when object-type-list is '*LIB' or 'LIB'.

*ALLSIMPLE The fastest approach to retrieving all user and system library names
in *SYSBAS and the current thread's ASP group. Values are returned
for the following columns: OBJNAME, OBJLONGNAME, OBJTYPE, OBJLIB,
OBJLONGSCHEMA, IASP_NUMBER, and IASP_NAME. All other columns
return NULL.

object- A character or graphic string expression containing one or more system object types
type-list separated by either a blank or a comma. The object types can include or exclude the leading
* character. The special value of '*ALL' or 'ALL' can be used to return all objects in the library
object-schema.
object- A character or graphic string expression that identifies the name of an object or a library. If
name the object's name is a delimited name, the delimited form of the name must be specified.
It can be either a long or short object name. The name must be the valid system name for
the object unless the object is a file or a library; for files and libraries the SQL name can be
specified.
A generic name can be specified to find multiple system objects. If the last character in the
name is an asterisk, the name is a generic name. For example, to return object names that
start with 'EMP', specify an object-name value of 'EMP*'. When a generic name is specified,
long SQL names are not included in the search.
If this parameter is specified, only objects with this name in object-schema corresponding to
the object types in object-type-list are returned.
If this parameter is not specified, all objects in object-schema corresponding to the object
types in object-type-list are returned.
If object-schema is *ALL, *ALLSIMPLE, *ALLAVL, *ALLUSR, or *ALLUSRAVL and object-type is
*LIB or LIB, the object-name parameter is ignored.

Database performance and query optimization 835


The following special value is allowed for object-name.

*ALLSIMPLE The fastest approach to retrieving the system names for objects in a library.
All objects in object-schema corresponding to the object types in object-type-
list are returned. Values are returned for the following columns: OBJNAME,
OBJTYPE, OBJLIB, OBJLONGSCHEMA, IASP_NUMBER, and IASP_NAME. All
other columns return NULL.

The result of the function is a table containing a row for each object with the format shown in the following
table. All the columns are null capable.
Table 201. OBJECT_STATISTICS table function

Column Name Data Type Description

OBJNAME VARCHAR(10) System name of the object.

OBJTYPE VARCHAR(8) System type of the object.

OBJOWNER VARCHAR(10) The user profile that owns the object.


Contains the null value if no owner is available.

OBJDEFINER VARCHAR(10) The user profile that created the object.


Contains the null value if the object definer is not known.

OBJCREATED TIMESTAMP Timestamp of when the object was created.

OBJSIZE DECIMAL(15,0) Size of the object, in bytes.

OBJTEXT VARCHAR(50) The description of the object.


Contains the null value if the object has no text.

OBJLONGNAME VARCHAR(128) The SQL name for the object.


For an external procedure or an external function, the name will be returned
when a single procedure or function exists for that *PGM or *SRVPGM object.
Contains the null value if an SQL name could not be returned.

LAST_USED_TIMESTAMP TIMESTAMP The date the object was used last. The time portion of the timestamp will always
be 0.
Contains the null value if the object has not been used.

LAST_USED_OBJECT VARCHAR(4) Indicates whether the LAST_USED_TIMESTAMP value is meaningful for this
object.

NO The object does not maintain the LAST_USED_TIMESTAMP.

YES The object maintains the LAST_USED_TIMESTAMP.

DAYS_USED_COUNT INTEGER The number of days an object has been used on the system.

LAST_RESET_TIMESTAMP TIMESTAMP The date when the days used count was last reset to zero. The time portion of the
timestamp will always be 0.
Contains the null value if the days used count has not been reset.

IASP_NUMBER SMALLINT The auxiliary storage pool (ASP) where storage is allocated for the object.

IASP_NAME VARCHAR(10) The device description name of the independent auxiliary storage pool (IASP).
The special value of *SYSBAS indicates SYSBASE, which includes the system ASP
(ASP 1) and the basic user ASPs (ASPs 2-32).

OBJATTRIBUTE VARCHAR(10) The attribute for this object's type, if any.


Contains an empty string if no attribute.

OBJLONGSCHEMA VARCHAR(128) The SQL schema name for this object.

TEXT VARGRAPHIC(50) CCSID The description of the object for *LIB objects.
1200
Contains the null value if OBJTYPE is not *LIB.

836 IBM i: Performance and Query Optimization


Table 201. OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

SQL_OBJECT_TYPE VARCHAR(9) The SQL type of the object. Values are:


• ALIAS
• FUNCTION
• INDEX
• PACKAGE
• PROCEDURE
• ROUTINE
• SEQUENCE
• TABLE
• TRIGGER
• TYPE
• VARIABLE
• VIEW
• XSR
Contains the null value if the object is not an SQL object.

OBJLIB VARCHAR(10) System name of the schema.

CHANGE_TIMESTAMP TIMESTAMP The timestamp of the last time the object was changed.

USER_CHANGED VARCHAR(3) Indicates whether the object was modified by a user. Values are:

NO The object was not modified by a user.

YES The object was modified by a user.

Contains the null value for certain objects that are installed as part of the
operating system.

SOURCE_FILE VARCHAR(10) The name of the source file that was used to create the object.
Contains the null value if a source file was not used.

SOURCE_LIBRARY VARCHAR(10) The name of the source file library that was used to create the object.
Contains the null value if a source file was not used.

SOURCE_MEMBER VARCHAR(10) The name of the source file member that was used to create the object.
Contains the null value if a source file was not used.

SOURCE_TIMESTAMP TIMESTAMP The last source update timestamp of the member in the source file at the time
the object was created.
Contains the null value if a source file was not used or if the source timestamp is
not available.

CREATED_SYSTEM VARCHAR(8) The name of the system on which the object was created.

CREATED_SYSTEM_VERSION VARCHAR(9) The version of the operating system when the object was created. The field has a
VxRxMx format where:

Vx The character V is followed by a version number.

Rx The character R is followed by a release level.

Mx The character M is followed by a modification level.

LICENSED_PROGRAM VARCHAR(7) The name of the licensed program if the object is part of a licensed program.
Contains the null value if the object is not a part of a licensed program.

LICENSED_PROGRAM_VERSION VARCHAR(9) The version number, release level, and modification level of the licensed program
if the object is part of a licensed program. The field has a VxRxMx format where:

Vx The character V is followed by a version number.

Rx The character R is followed by a release level.

Mx The character M is followed by a modification level.

Contains the null value if the object is not a part of a licensed program.

COMPILER VARCHAR(7) The licensed program identifier of the compiler.


Contains the null value if the object was not created with a compiler.

Database performance and query optimization 837


Table 201. OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

COMPILER_VERSION VARCHAR(9) The licensed program version number, release level, and modification level of the
compiler. The field has a VxRxMx format where:

Vx The character V is followed by a version number.

Rx The character R is followed by a release level.

Mx The character M is followed by a modification level.

Contains the null value if the object was not created with a compiler.

OBJECT_CONTROL_LEVEL CHAR(8) The object control level for the object.


Contains the null value if there is no object control level.

PTF_NUMBER CHAR(7) The Program Temporary Fix that resulted in the creation of this object.
Contains the null value for a user created object.

APAR_ID CHAR(6) The authorized program analysis report (APAR) with this identification number
associated with the last change.
Will contain the value CHGDFT for a command that is changed using
CHGCMDDFT.
The Change Object Description (QLICOBJD) API can change this field to any
value.
Contains the null value is no value is available.

USER_DEFINED_ATTRIBUTE VARCHAR(10) Further defines an object type. This field is set by the user by using the
QLICOBJD API.
Contains the null value if the attribute has not been set.

ALLOW_CHANGE_BY_PROGRAM VARCHAR(3) Identifies whether or not any changes other than the text or the days used count
and reset date can be made to the object's description by the Change Object
Description (QLICOBJD) API.

NO The QLICOBJD API cannot be used to change fields in the object's


description other than the text or the days used count and reset date.

YES The QLICOBJD API can be used to change fields in the object's
description.

CHANGED_BY_PROGRAM VARCHAR(3) Identifies whether the object has been modified by the Change Object
Description (QLICOBJD) API.

NO The object has not been modified by the QLICOBJD API.

YES The object has been modified by the QLICOBJD API.

COMPRESSED VARCHAR(4) Indicates whether the object is compressed or decompressed. Values are:

NO Permanently decompressed and compressible.

YES Compressed.

TEMP Temporarily decompressed.

FREE Saved with storage freed; compression status cannot be determined.

Contains the null value if the object is permanently decompressed and not
compressible.

PRIMARY_GROUP VARCHAR(10) The name of the user profile that is the primary group for the object.
Contains the null value if there is no primary group for the object.

STORAGE_FREED VARCHAR(3) The storage status of the object data.

NO The storage for the object data has not been freed.

YES The storage for the object data has been freed. See the SAVOBJ or
SAVLIB command, STG parameter, for more details.

ASSOCIATED_SPACE_SIZE INTEGER The size, in bytes, of the primary associated space of the object.
Contains the null value if the object has no primary associated space.

838 IBM i: Performance and Query Optimization


Table 201. OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

OPTIMUM_SPACE_ALIGNMENT VARCHAR(3) Identifies whether the primary associated space for the object has been
optimally aligned. Optimum alignment may allow for better performance of
applications that manipulate the object.

NO The space associated with the object has not been optimally aligned.

YES The space associated with the object has been optimally aligned.

Contains the null value if the object has no associated space.

OVERFLOW_STORAGE VARCHAR(3) Indicates if the object has overflowed the auxiliary storage pool it resides in.

NO The object has not overflowed the auxiliary storage pool.

YES The object has overflowed the auxiliary storage pool.

OBJECT_DOMAIN VARCHAR(7) The domain that contains the object. Values are:

*SYSTEM The object is in the system domain.

*USER The object is in the user domain.

OBJECT_AUDIT VARCHAR(10) The type of auditing for an object. Values are:

*NONE No auditing occurs for this object when it is read or changed


regardless of the user who is accessing the object.

*USRPRF Audit this object only if the current user is being audited. The
current user is tested to determine if auditing should be done for
this object. The user profile can specify if only change access is
audited or if both read and change accesses are audited for this
object.

*CHANGE Audit all change access to this object by all users on the system.

*ALL Audit all access to this object by all users on the system. All access
is defined as a read or change operation.

Contains the null value if you do not have either all object (*ALLOBJ) or audit
(*AUDIT) special authority.

OBJECT_SIGNED VARCHAR(3) Indicates whether the object has a digital signature.

NO The object does not have a digital signature.

YES The object has a digital signature.

SYSTEM_TRUSTED_SOURCE VARCHAR(3) Indicates whether the object is signed by a source that is trusted by the system.

NO None of the object signatures came from a source that is trusted by the
system.

YES The object is signed by a source that is trusted by the system. If the
object has multiple signatures, at least one of the signatures came from
a source that is trusted by the system.

MULTIPLE_SIGNATURES VARCHAR(3) Indicates whether the object has more than one digital signature.

NO The object has only one digital signature or does not have a digital
signature.

YES The object has more than one digital signature.

SAVE_TIMESTAMP TIMESTAMP The timestamp the object was last saved.


Contains the null value if the object has not been saved.

RESTORE_TIMESTAMP TIMESTAMP The timestamp the object was last restored.


Contains the null value if the object has not been restored.

SAVE_WHILE_ACTIVE_TIMESTAMP TIMESTAMP The timestamp at which the object was saved while active.
Contains the null value if the object has not been saved while active.

SAVE_COMMAND VARCHAR(10) The command used to save the object.


Contains the null value if the object has not been saved.

Database performance and query optimization 839


Table 201. OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

SAVE_DEVICE VARCHAR(5) The type of the device to which the object was last saved. Valid values are:

*OPT The object was saved to optical.

*SAVF The object was saved to a save file.

*TAP The object was saved to tape.

Contains the null value if the object has not been saved.

SAVE_FILE_NAME VARCHAR(10) The save file used to save the object.


Contains the null value if the object was not last saved to a save file.

SAVE_FILE_LIBRARY VARCHAR(10) The save file library used to save the object.
Contains the null value if the object was not last saved to a save file.

SAVE_VOLUME VARCHAR(71) The tape or optical volumes used to save the object. A maximum of ten volumes
is returned. The string contains one blank between volume identifiers. If more
than ten volumes were used, an ellipsis (three periods) is returned to the right of
the identifier of the tenth volume.
Contains the null value if the object was not last saved to tape or optical.

SAVE_LABEL VARCHAR(17) The file label used when the object was saved to tape or optical.
Contains the null value if the object was not last saved to tape or optical.

SAVE_SEQUENCE_NUMBER DECIMAL(10,0) The sequence number used to when the object was saved to tape.
Contains the null value if the object was not last saved to tape.

LAST_SAVE_SIZE DECIMAL(15,0) The size of the object in bytes at the time of the last save. This value defines the
amount of storage that is required if the object is restored.
Contains the null value if the object has not been saved.

JOURNALED VARCHAR(3) Identifies the current journaling status of the object. Valid values are:

NO The object is not currently journaled.

YES The object is currently journaled.

JOURNAL_NAME VARCHAR(10) The name of journal that receives the journaled changes or the name of the last
journal if the object is not currently journaled.
Contains the null value if the object has not been journaled.

JOURNAL_LIBRARY VARCHAR(10) The name of journal library that receives the journaled changes or the name of
the last journal library if the object is not currently journaled.
Contains the null value if the object has not been journaled.

JOURNAL_IMAGES VARCHAR(6) Specifies the kinds of images that are generated for changes to the object. Valid
values are:

*AFTER Only after images are generated for changes to the object.

*BOTH Both before and after images are generated for changes to the
object.

Contains the null value if the object has not been journaled.

OMIT_JOURNAL_ENTRY VARCHAR(7) Specifies the journal entries that are omitted. Valid values are:

*NONE No journal entries are omitted.

*OPNCLO Open and close entries are omitted. Open and close operations on
the specified file members do not create open and close journal
entries.

Contains the null value if the object has not been journaled.

REMOTE_JOURNAL_FILTER VARCHAR(3) The remote journal filter value for the object. Valid values are:

NO The journal entries deposited for the object will not be eligible for remote
journal filtering.

YES The journal entries deposited for the object will be eligible for remote
journal filtering.

Contains the null value if the object has not been journaled.

840 IBM i: Performance and Query Optimization


Table 201. OBJECT_STATISTICS table function (continued)

Column Name Data Type Description

JOURNAL_START_TIMESTAMP TIMESTAMP The timestamp journaling was last started.


Contains the null value if the object has not been journaled.

APPLY_STARTING_RECEIVER VARCHAR(10) Specifies the name of the oldest journal receiver needed to successfully use
the Apply Journaled Changes (APYJRNCHG) or Remove Journaled Changes
(RMVJRNCHG) command.
Contains the null value if the object has not been journaled or it has not been
saved and restored since journaling was started.

APPLY_STARTING_RECEIVER_LIBRARY VARCHAR(10) Specifies the library name of the oldest journal receiver needed to successfully
use the Apply Journaled Changes (APYJRNCHG) or Remove Journaled Changes
(RMVJRNCHG) command.
Contains the null value if the object has not been journaled or it has not been
saved and restored since journaling was started.

AUTHORITY_COLLECTION_VALUE VARCHAR(10) Specifies the authority collection value used for the object when authority
collection for objects is active on the partition. Valid values are:

*NONE No authority information will be collected for this object when


authority collection for objects is active on the partition.
A value of *NONE will be returned if the object type is not
supported by authority collection.

*OBJINF Authority information will be collected for this object when


authority collection for objects is active on the partition. The
authority checking information is collected for each unique instance
of the object level information associated with the authority check.

Example
• Find all journals in library MJATST.

SELECT * FROM TABLE (QSYS2.OBJECT_STATISTICS('MJATST ','JRN') ) AS X

or

SELECT * FROM TABLE (QSYS2.OBJECT_STATISTICS('MJATST ','*JRN') ) AS X

• Find all journals and journal receivers in library MJATST.

SELECT * FROM TABLE (QSYS2.OBJECT_STATISTICS('MJATST ','JRN JRNRCV') ) AS X

or

SELECT * FROM TABLE (QSYS2.OBJECT_STATISTICS('MJATST ','*JRN *JRNRCV') ) AS X

• Find all programs and service programs in library MYLIB. Use *ALLSIMPLE to return the list quickly,
omitting the detail information.

SELECT * FROM TABLE (QSYS2.OBJECT_STATISTICS('MYLIB','PGM SRVPGM','*ALLSIMPLE')) X

• Find any CL commands that have had their parameter defaults changed.

SELECT * FROM TABLE(QSYS2.OBJECT_STATISTICS('QSYS', '*CMD'))


WHERE APAR_ID = 'CHGDFT';

SYSTEM_OBJECT_TYPES table
The SYSTEM_OBJECT_TYPES table returns a list of external object types found on IBM i.
Additional information about object types is available at this link: External object types
Authorization: None required.
The following table describes the columns in the table. The system name is OBJ_TYPES. The schema is
QSYS2.

Database performance and query optimization 841


Table 202. SYSTEM_OBJECT_TYPES table

System Column
Column Name Name Data Type Description

OBJECT_TYPE OBJTYPE VARCHAR(7) System object type.

TEXT_DESCRIPTION TEXT VARCHAR(60) Description of the object type.

CATEGORY CATEGORY VARCHAR(7) Category of object type.

IFS The object type resides in the integrated file system


(IFS).

LIBRARY The object type resides in a library.

Example
List all the system object types that are found in libraries:

SELECT * FROM QSYS2.SYSTEM_OBJECT_TYPES


WHERE CATEGORY = 'LIBRARY';

Message Handling Services


These views and functions provide system message information.

HISTORY_LOG_INFO table function


The HISTORY_LOG_INFO table function returns one row for each message in the history log based on the
timestamp range specified. It returns information similar to what is returned by the Display Log (DSPLOG)
CL command and the Open List of History Log Messages (QMHOLHST) API.
Authorization: None required.

HISTORY_LOG_INFO (
start-time
START_TIME =>

, end-time
END_TIME =>

, generate-syslog
GENERATE_SYSLOG =>

)
, eof-delay
EOF_DELAY =>

The schema is QSYS2.

start-time A timestamp expression that indicates the starting timestamp to use when returning
history log information.
If this parameter is omitted, the default of CURRENT DATE - 1 DAY is used.

end-time A timestamp expression that indicates the ending timestamp to use when returning history
log information.

842 IBM i: Performance and Query Optimization


If this parameter is omitted, the default of '9999-12-30-00.00.00.000000' is used.

generate- A character or graphic string expression that indicates whether to transform history log
syslog messages into syslog formatted detail. Values are:

NO No syslog information will be returned. The SYSLOG_EVENT,


SYSLOG_FACILITY, SYSLOG_SEVERITY, and SYSLOG_PRIORITY columns will
contain the null value.
RFC3164 Values will be returned for the SYSLOG_EVENT, SYSLOG_FACILITY,
SYSLOG_SEVERITY, and SYSLOG_PRIORITY columns for each history log
message. The SYSLOG_EVENT column will contain a syslog header that
matches the RFC3164 format as described by the Internet Engineering Task
Force (IETF) Request For Comments (RFC) 3164.
RFC5424 Values will be returned for the SYSLOG_EVENT, SYSLOG_FACILITY,
SYSLOG_SEVERITY, and SYSLOG_PRIORITY columns for each history log
message. The SYSLOG_EVENT column will contain a syslog header that
matches the RFC5424 format as described by the Internet Engineering Task
Force (IETF) Request For Comments (RFC) 5424.

If generate-syslog is not specified or is the null value, NO is used.

eof-delay An integer expression that specifies the number of seconds to sleep when all history log
messages have been read. This delay allows the caller to establish a polling service that
will continually return rows, sleeping for the specified interval whenever all messages have
been processed.
A value of zero indicates no delay is used and a finite set of rows will be returned. A value
greater than zero indicates that the table function will sleep, as needed, to wait for new
history log messages and never end. If eof-delay is not specified or is the null value, zero is
used.
If this parameter has a value greater than zero, the generate-syslog parameter must be
RFC3164 or RFC5424, and the end-time parameter cannot be specified with a value other
than its default value.
When using a non-zero eof-delay parameter, avoid using query clauses that depend on
returning a finite number of rows. For example, using the FETCH FIRST n ROWS clause
can cause the query to end when the requested number of rows has been satisfied. A
query using the HISTORY_LOG_INFO function with a non-zero eof-delay parameter does
not allow data to be copied (ALWCPYDTA(*NO)). This means that a query requiring a copy
of data, such as one using an ORDER BY clause or UNION DISTINCT, will issue an error and
not be allowed. When using eof-delay, consider using a simple query to avoid blocking of
rows. When rows are blocked for data transport efficiency, rows won't be returned until the
block is full. Therefore, you should decide whether you favor data transport efficiency or
moving events as soon as they occur.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 203. HISTORY_LOG_INFO table function

Column Name Data Type Description

ORDINAL_POSITION INTEGER A unique number for each row that indicates the time order of
messages in the job log. The first (oldest) message returned from the
history log will have a value of 1. Subsequent messages will have a
value one greater than the previous message. Since these values are
assigned when this catalog is queried, there will be no gaps in values.

MESSAGE_ID VARCHAR(7) The message ID for this message.


Contains the null value if this is an impromptu message or
MESSAGE_TYPE is REPLY.

Database performance and query optimization 843


Table 203. HISTORY_LOG_INFO table function (continued)

Column Name Data Type Description

MESSAGE_TYPE VARCHAR(13) Type of message.


• COMPLETION
• DIAGNOSTIC
• ESCAPE
• INFORMATIONAL
• INQUIRY
• NOTIFY
• REPLY
• REQUEST
• SENDER

MESSAGE_SUBTYPE VARCHAR(22) Subtype of message.


The values returned for REPLY messages:
• FROM EXIT PROGRAM
• FROM SYSTEM REPLY LIST
• MESSAGE DEFAULT USED
• NOT VALIDITY CHECKED
• SYSTEM DEFAULT USED
• VALIDITY CHECKED
The value returned for some REQUEST messages:
• WITH PROMPTING
Contains the null value for other message types.

SEVERITY SMALLINT The severity assigned to the message.

MESSAGE_TIMESTAMP TIMESTAMP The timestamp when the message was sent.

FROM_USER VARCHAR(10) The current user of the job when the message was sent.

FROM_JOB VARCHAR(28) The qualified job name when the message was sent.

FROM_JOB_NAME VARCHAR(10) The name of the job when the message was sent.

FROM_JOB_USER VARCHAR(10) The user profile that started the job when the message was sent.

FROM_JOB_NUMBER VARCHAR(6) The job number of the job when the message was sent.

FROM_PROGRAM VARCHAR(10) The program that sent the message.

MESSAGE_LIBRARY VARCHAR(10) The name of the library containing the message file.
Contains the null value if MESSAGE_ID is null.

MESSAGE_FILE VARCHAR(10) The message file containing the message.


Contains the null value if MESSAGE_ID is null.

MESSAGE_TOKENS VARCHAR(4096) FOR BIT DATA The message token string. If the value is longer than 4096 characters,
it will be truncated with no warning.
Contains the null value if there are no message tokens.

MESSAGE_TEXT VARGRAPHIC(1024) CCSID 1200 The first level text of the message including tokens, or the impromptu
message text.
Contains the null value if MESSAGE_ID is null or if the message file
could not be accessed.

MESSAGE_SECOND_LEVEL_TEXT VARGRAPHIC(4096) CCSID 1200 The second level text of the message including tokens.
Contains the null value if MESSAGE_ID is null or if the message has no
second level text or if the message file could not be accessed.

844 IBM i: Performance and Query Optimization


Table 203. HISTORY_LOG_INFO table function (continued)

Column Name Data Type Description

SYSLOG_EVENT VARGRAPHIC(2048) CCSID 1200 The Common Event Format (CEF) syslog event for the message
preceded by a header of the requested type. If a header-type of
RFC3164 is requested, the maximum length is 1024 characters. If
a header-type of RFC5424 is requested, the maximum length is 2048
characters. The string will be truncated with no warning if it exceeds
the maximum length.
The key names returned for history log information are listed in the
Notes section.
Contains the null value if NO was specified for the
GENERATE_SYSLOG parameter.

SYSLOG_FACILITY INTEGER The syslog facility assigned to the event.

1 user-level messages

4 security/authorization messages

The facility assigned is defined in the Notes section.


Contains the null value if NO was specified for the
GENERATE_SYSLOG parameter.

SYSLOG_SEVERITY INTEGER The syslog severity assigned to the event.

1 Alert: Action must be taken immediately

3 Error condition

4 Warning condition

5 Notice: A normal but significant condition

6 Informational message

7 Debug level message

The severity assigned is listed in the Notes section.


Contains the null value if NO was specified for the
GENERATE_SYSLOG parameter.

SYSLOG_PRIORITY INTEGER The syslog priority number assigned to the event.


Contains the null value if NO was specified for the
GENERATE_SYSLOG parameter.

Notes
Syslog information: Syslog information is returned for all messages in the history log. Syslog information
is also available for audit journal entries. See DISPLAY_JOURNAL table function for more details.
All history log messages return a SYSLOG_FACILITY value of 1 except as noted below. Messages are
assigned a SYSLOG_SEVERITY value in the following way:
• Severity 1 Alert: Action must be taken immediately
– MESSAGE_TYPE contains a value of INQUIRY, NOTIFY, or REPLY
• Severity 3 Error condition
– MESSAGE_ID contains a value of CPF1164 with a job ending code value in the MESSAGE_TEXT
column of 30 or higher
– MESSAGE_TYPE contains a value of ESCAPE when the SEVERITY column contains a value of 50 or
greater
• Severity 4 Warning condition
– MESSAGE_ID contains a value of CPF1393. The SYSLOG_FACILITY column is set to 4.
– MESSAGE_ID contains a value of CPF1164 with a job ending code value in the MESSAGE_TEXT
column of 20
– MESSAGE_TYPE contains a value of ESCAPE when the SEVERITY column contains a value of 30 or
greater but less than 50

Database performance and query optimization 845


• Severity 5 Notice: A normal but significant condition
– MESSAGE_ID contains a value of CPF1164 with a job ending code value in the MESSAGE_TEXT
column of 10
– MESSAGE_TYPE contains a value of INFORMATIONAL, COMPLETION, DIAGNOSTIC, or REQUEST
when the SEVERITY column contains a value of 50 or greater
• Severity 6 Informational message
– MESSAGE_ID contains a value of CPF1164 with a job ending code value in the MESSAGE_TEXT
column of 0
– MESSAGE_TYPE contains a value of ESCAPE when the SEVERITY column contains a value less than
30
– MESSAGE_TYPE contains a value of SENDER
– MESSAGE_TYPE contains a value of INFORMATIONAL, COMPLETION, DIAGNOSTIC, or REQUEST
when the SEVERITY column contains a value less than 50
• Severity 7 Debug level message
– MESSAGE_ID contains a value of CPF9897 or CPF9898 (regardless of severity or message type)
The Common Event Format key names that are generated within the SYSLOG_EVENT column are:

Table 204. Common Event Format key names


Common Event Format key name Description
msg The message text (MESSAGE_TEXT column) from
the history log message
reason Text description of the history log message
sproc The qualified job name (FROM_JOB column) from
the history log message
suser Current user name (FROM_USER column) from the
history log message

Examples
• Return a list of history log messages for all of yesterday and today.

SELECT * FROM TABLE(QSYS2.HISTORY_LOG_INFO()) X

• Return a list of all history log messages for the last 24 hours.

SELECT * FROM TABLE(QSYS2.HISTORY_LOG_INFO(CURRENT TIMESTAMP - 1 DAY)) X

• Return history log information since the last IPL, assuming that the last IPL timestamp is in a global
variable named LAST_IPL_TIME.

SELECT * FROM TABLE(QSYS2.HISTORY_LOG_INFO(LAST_IPL_TIME, CURRENT TIMESTAMP)) A

• Return syslog information formatted with an RFC3164 header for all history log messages from the start
of today forward into the future. When all history log messages have been returned to the caller, the
query will pause for 5 minutes (300 seconds) before checking again for messages.

SELECT syslog_facility, syslog_severity, syslog_event


FROM TABLE (QSYS2.HISTORY_LOG_INFO(START_TIME => CURRENT DATE,
GENERATE_SYSLOG =>'RFC3164',
EOF_DELAY => 300
) ) AS X;

846 IBM i: Performance and Query Optimization


JOBLOG_INFO table function
The JOBLOG_INFO table function returns one row for each message in a job log.
The values returned for the table function columns are closely related to the values returned by the
Display Job Log (DSPJOBLOG) CL command.
Authorization:
• None required to see job log information for jobs where the caller's user profile is the same as the job
user identity of the job for which the information is being returned.
• If the job user identity of the job for which the information is being returned has *ALLOBJ
special authority, the caller must have *ALLOBJ special authority or be authorized to the
QIBM_ACCESS_ALLOBJ_JOBLOG function usage identifier.
• Otherwise, the caller must have *JOBCTL special authority.

JOBLOG_INFO ( job-name
JOB_NAME =>

)
, ignore-errors
IGNORE_ERRORS =>

The schema is QSYS2.

job-name A character or graphic string expression that identifies the qualified name of a job. The
special value of '*' indicates the current job.
ignore-errors A character or graphic string expression that identifies what to do when an error is
encountered.

NO An error is returned. This is the default.


YES A warning is returned. No rows are returned when an error is encountered.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 205. JOBLOG_INFO table function

Column Name Data Type Description

ORDINAL_POSITION INTEGER A unique number for each row that indicates the time order of
messages in the job log. The first (oldest) message in the job log will
have a value of 1. Subsequent messages will have a value one greater
than the previous message. Since these values are assigned when this
catalog is queried, there will be no gaps in values. There is no visibility
of messages that have been deleted from the job log.

MESSAGE_ID VARCHAR(7) The message ID for this message.


Contains the null value if this is an impromptu message or a REQUEST
message.

Database performance and query optimization 847


Table 205. JOBLOG_INFO table function (continued)

Column Name Data Type Description

MESSAGE_TYPE VARCHAR(13) Type of message. Values are:


• COMMAND
• COMPLETION
• DIAGNOSTIC
• ESCAPE
• INFORMATIONAL
• INQUIRY
• NOTIFY
• REPLY
• REQUEST
• SCOPE
• SENDER

MESSAGE_SUBTYPE VARCHAR(22) Subtype of message.


Values for NOTIFY or ESCAPE messages are:
• EXCEPTION HANDLED
• EXCEPTION NOT HANDLED
Values for REPLY messages are:
• FROM EXIT PROGRAM
• FROM SYSTEM REPLY LIST
• MESSAGE DEFAULT USED
• NOT VALIDITY CHECKED
• SYSTEM DEFAULT USED
• VALIDITY CHECKED
Contains the null value for other message types.

SEVERITY SMALLINT The severity assigned to the message.

MESSAGE_TIMESTAMP TIMESTAMP The timestamp for when the message was issued.

FROM_LIBRARY VARCHAR(10) The library containing the program or service program that sent the
message.

FROM_PROGRAM VARCHAR(256) The program or service program name that sent the message.

FROM_MODULE VARCHAR(10) The module that sent the message.

FROM_PROCEDURE VARCHAR(4096) The procedure that sent the message.

FROM_INSTRUCTION VARCHAR(10) The instruction that sent the message.

TO_LIBRARY VARCHAR(10) The library containing the program or service program that received
the message

TO_PROGRAM VARCHAR(10) The program or service program name that received the message.

TO_MODULE VARCHAR(10) The module that received the message.

TO_PROCEDURE VARCHAR(4096) The procedure that received the message.

TO_INSTRUCTION VARCHAR(10) The instruction that received the message.

FROM_USER VARCHAR(10) The userid of the job when the message was sent.

MESSAGE_FILE VARCHAR(10) The message file containing the message.

MESSAGE_LIBRARY VARCHAR(10) The name of the library containing the message file.

MESSAGE_TOKEN_LENGTH SMALLINT The length of the MESSAGE_TOKENS string.

MESSAGE_TOKENS VARCHAR(2048) FOR BIT DATA The message token string. If the value is longer than 2048 characters,
it will be truncated with no warning.

MESSAGE_TEXT VARGRAPHIC(1024) CCSID 1200 The first level text of the message including tokens.

MESSAGE_SECOND_LEVEL_TEXT VARGRAPHIC(4096) CCSID 1200 The second level text of the message including tokens.

MESSAGE_KEY BINARY(4) The key assigned to the message.


The key is assigned by the command or API that sends the message.

848 IBM i: Performance and Query Optimization


Table 205. JOBLOG_INFO table function (continued)

Column Name Data Type Description

QUALIFIED_JOB_NAME VARCHAR(28) The qualified name of the job for this job log.

Examples
• Return joblog information for job 347117/QUSER/QZDASOINIT.

SELECT * FROM TABLE(QSYS2.JOBLOG_INFO('347117/QUSER/QZDASOINIT')) A

• Extract the last command entered by the user.

SELECT MESSAGE_TEXT FROM TABLE(QSYS2.JOBLOG_INFO('817029/QUSER/QPADEV0004')) A


WHERE A.MESSAGE_TYPE = 'REQUEST'
ORDER BY ORDINAL_POSITION DESC
FETCH FIRST 1 ROW ONLY

MESSAGE_FILE_DATA view
The MESSAGE_FILE_DATA view returns one row for each message in a message file.
The information is similar to what is returned by the Display Message Description (DSPMSGD) CL
command and the Retrieve Message (QMHRTVM) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the message file, and
• *USE authority to the message file.
The following table describes the columns in the view. The system name is MSGF_DATA. The schema is
QSYS2.
Table 206. MESSAGE_FILE_DATA view

Column Name System Column Name Data Type Description

MESSAGE_FILE_LIBRARY MSGF_LIB VARCHAR(10) The library containing the message file.

MESSAGE_FILE MSGF VARCHAR(10) The message file.

MESSAGE_ID MSGID CHAR(7) The message identifier.

MESSAGE_TEXT MSG_TEXT VARGRAPHIC(132) The text of the message.


CCSID 1200

MESSAGE_SECOND_LEVEL_ SECLVL VARGRAPHIC(300 The second-level message text of the message.


TEXT 0) CCSID 1200
Contains the null value if no second-level text is defined.
Nullable

SEVERITY SEVERITY INTEGER The severity of the message.

MESSAGE_DATA_COUNT MSGDATACNT INTEGER The number of variables defined in MESSAGE_DATA.

MESSAGE_DATA MSGDATA VARCHAR(2078) A string containing all the message data fields, also referred to
as substitution variables, for the message. The format of the
Nullable string is described following this table.
Contains the null value if no message data fields are defined.

LOG_PROBLEM LOGPRB VARCHAR(4) The log problem value for the message.

*NO Problems are not logged.

*YES Problems are logged.

CREATION_DATE CRT_DATE DATE The date the message was created.

CREATION_LEVEL CRT_LEVEL INTEGER The level number of the message. This is a value from 1 to 99.

MODIFICATION_DATE MOD_DATE DATE The date the message was modified.

MODIFICATION_LEVEL MOD_LEVEL INTEGER The modification level number of the message. This is a value
from 1 to 99.

Database performance and query optimization 849


Table 206. MESSAGE_FILE_DATA view (continued)

Column Name System Column Name Data Type Description

CCSID CCSID INTEGER The CCSID that applies to the stored values of MESSAGE_TEXT
and MESSAGE_SECOND_LEVEL_TEXT.

DEFAULT_PROGRAM_LIBRARY DFT_PGMLIB VARCHAR(10) The library specified for the default program. Can contain the
following special values:
Nullable
*CURLIB The current library is used.

*LIBL The program is found using the library list.

Contains the null value if no default program is defined.

DEFAULT_PROGRAM DFT_PGM VARCHAR(10) The name of the program called to take default action if
this message is sent as an escape message to a program or
Nullable procedure that is not monitoring for it.
Contains the null value if no default program is defined.

REPLY_TYPE REPLY_TYPE VARCHAR(6) The type of valid values that can be made to an inquiry or notify
message.
Nullable
*ALPHA Only an alphabetic string is valid. Blanks are not
allowed.

*CHAR Any character string is valid. If it is a quoted


character string, the apostrophes are passed as part
of the character string.

*DEC Only a decimal number is a valid reply.

*NAME Only a simple name is a valid reply. The name does


not have to be an object name, but it must start with
an alphabetic character; the remaining characters
must be alphanumeric.

Contains the null value if there is no reply type.

REPLY_LENGTH REPLY_LEN INTEGER The maximum length of a reply to an inquiry or notify message.

Nullable Contains the null value if there is no reply type.

REPLY_DECIMAL_POSITIONS REPLY_DEC INTEGER The maximum number of decimal positions allowed in the
message reply.
Nullable
Contains the null value if there is no reply type or if REPLY_TYPE
is not *DEC.

DEFAULT_REPLY DFT_REPLY VARCHAR(132) The default reply for the message.

Nullable Contains the null value if no default reply is defined.

VALID_REPLY_VALUES_COUNT REPLY_CNT INTEGER The number of entries returned in VALID_REPLY_VALUES.

VALID_REPLY_VALUES REPLY_VALS VARCHAR(659) The list of valid reply values. Each value is a character string with
a length of 32. One blank separates values.
Nullable
Contains the null value if no valid reply values are defined.

VALID_REPLY_LOWER_LIMIT LOWERLIMIT VARCHAR(32) The lower value limit for a valid reply.

Nullable Contains the null value if no range values for replies are defined.

VALID_REPLY_UPPER_LIMIT UPPERLIMIT VARCHAR(32) The upper value limit for a valid reply.

Nullable Contains the null value if no range values for replies are defined.

VALID_REPLY_RELATIONSHIP_ REL_OP CHAR(3) The relational operator for a relational test entry.
OPERATOR Nullable *EQ Equal to

*GE Greater than or equal to

*GT Greater than

*LE Less than or equal to

*LT Less than

*NE Not equal to

Contains the null value if no relationship for valid replies is


defined.

850 IBM i: Performance and Query Optimization


Table 206. MESSAGE_FILE_DATA view (continued)

Column Name System Column Name Data Type Description

VALID_REPLY_RELATIONSHIP_ REL_VALUE VARCHAR(32) The value to be compared to the reply entered for a relational
VALUE test entry.
Nullable
Contains the null value if no relationship for valid replies is
defined.

SPECIAL_REPLY_VALUES_COUNT SPECIALCNT INTEGER The number of entries returned in SPECIAL_REPLY_VALUES.

SPECIAL_REPLY_VALUES SPECIALVAL VARCHAR(1319) The list of special reply values. Each pair of values consists of
the from-value followed by a colon (:) followed by the to-value.
Nullable One blank separates each pair of values.
Contains the null value if no special reply values are defined.

DUMP_LIST_COUNT DUMP_COUNT INTEGER The number of entries returned in DUMP_LIST.

DUMP_LIST DUMP_LIST VARCHAR(815) The list of data items to be dumped when the message is sent
as an escape message to a program that is not monitoring for it.
Nullable The list contains entries separated by a single blank.

1-99 The number of the message data field that is to be


dumped.

*JOB The job information produced by the Display Job


(DSPJOB) command is printed.

*JOBDMP The data areas of the job are dumped as specified


by the Dump Job (DMPJOB) command.

*JOBINT The internal machine data structures related to


the machine process in which the job is running
are dumped to the machine error log.

Contains the null value if there is no dump list for this message.

ALERT_OPTION ALERTOPT VARCHAR(9) Whether an alert is sent for the message.

*DEFER An alert is sent after local problem analysis.

*IMMED An alert is sent immediately when the message


is sent to a message queue that has the allow
alerts attribute set to *YES.

*NO No alert is sent.

*UNATTEND An alert is sent immediately when the system is


running in unattended mode.

ALERT_INDEX ALERTINDEX INTEGER The number of the message data field that is passed with the
alert.
Nullable
Contains the null value if no alert is sent or no message data
field is passed with the alert.

The MESSAGE_DATA column contains all of the substitution variables formatted as follows. A single blank
separates each variable attribute. There is one blank between each variable definition. The order of the
attributes is:
1. Variable identifier, such as &1.
2. Data type of the variable.

*BIN A binary value formatted in the message as a signed decimal value.


*CCHAR A convertible character string.
*CHAR A character string formatted without enclosing apostrophes.
*DEC A packed decimal number that is formatted in the message as a signed decimal value
with a decimal point.
*DTS An 8-byte field that contains a system date/time stamp and is formatted in the message
as the date followed by one blank and then the time.
*HEX A string of bytes formatted as a hexadecimal value.

Database performance and query optimization 851


*ITV An 8-byte binary field that contains the time interval (in seconds) for wait time-out
conditions.
*QTDCHAR A character string formatted with enclosing apostrophes.
*SPP A 16-byte space pointer to data in a space object.
*SYP A 16-byte system pointer to a system object.
*UBIN A binary value formatted in the message as an unsigned decimal value
*UTC An 8-byte field that contains a system date/time stamp in Coordinated Universal Time
(UTC) and is formatted in the message as the date followed by one blank and then the
time. Before the output formatting the date/time stamp is adjusted from UTC using the
time zone specified for the job.
*UTCD An 8-byte field that contains a system date/time stamp in Coordinated Universal Time
(UTC) and is formatted in the message as a date with no time. Before the output
formatting the date/time stamp is adjusted from UTC using the time zone specified for
the job.
*UTCT An 8-byte field that contains a system date/time stamp in Coordinated Universal Time
(UTC) and is formatted in the message as a time with no date. Before the output
formatting the date/time stamp is adjusted from UTC using the time zone specified for
the job.
3. Length, if applicable.
• *VARY or the length of the substitution variable.
4. Additional length information, if applicable.
• Fractional digits for a *DEC variable
• 2 or 4 when the length is *VARY
For example, when there are two substitution variables, one a varying character and one a four byte
integer, the string might look like this.

&1 *CHAR *VARY 2 &2 *BIN 4

Example
Find any messages in the APPLIB/APPMSGS message file that contain the word VALUE in upper case,
lower case, or mixed case in either the message text or the second level message text.

SELECT * FROM QSYS2.MESSAGE_FILE_DATA


WHERE MESSAGE_FILE_LIBRARY = 'APPLIB' AND MESSAGE_FILE = 'APPMSGS' AND
(UPPER(MESSAGE_TEXT) LIKE '%VALUE%' OR
UPPER(MESSAGE_SECOND_LEVEL_TEXT) LIKE '%VALUE%');

MESSAGE_QUEUE_INFO table function


The MESSAGE_QUEUE_INFO table function returns one row for each message in a specific message
queue. It returns information similar to what is returned by the Display Messages (DSPMSG) CL command
and the Receive Nonprogram Message (QMHRCVM) and Open List of Messages (QGYOLMSG) APIs.
This table function does not change the contents of the message queue. The message is kept in the
message queue without changing its new or old designation.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the message queue, and
• *USE authority to the message queue

852 IBM i: Performance and Query Optimization


MESSAGE_QUEUE_INFO (
message-queue-library
QUEUE_LIBRARY =>

, message-queue-name
QUEUE_NAME =>

, message-filter
MESSAGE_FILTER =>

)
, severity-filter
SEVERITY_FILTER =>

The schema is QSYS2.

message- A character or graphic string expression that contains the name of the library containing
queue-library message-queue-name. If omitted, the default is QSYS.
message- A character or graphic string expression that contains the name of a message queue. If
queue-name omitted, the default is QSYSOPR.
message-filter A character or graphic string expression that indicates the type of messages to be
returned. The string can contain one or more of the following values separated by
blanks. Specifying 'COMPLETE INQUIRY SENDER' is the same as specifying ALL.

ALL All messages are returned. This is the default.


COMPLETE Only messages that do not require a reply are returned.
INQUIRY Only inquiry messages that require a reply are returned.
SENDER Only copies of the inquiry messages that were sent to other message
queues and still require a reply are returned.

severity-filter An integer value indicating the minimum severity of messages to be returned. The value
must be from 0 to 99. The default is 0, indicating all messages are to be returned.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 207. MESSAGE_QUEUE_INFO table function

Column Name Data Type Description

MESSAGE_ID VARCHAR(7) The message ID for this message.


Contains the null value if this is an impromptu message or MESSAGE_TYPE is
REPLY.

MESSAGE_TYPE VARCHAR(13) Type of message. Values are:


• COMPLETION
• DIAGNOSTIC
• ESCAPE
• INFORMATIONAL
• INQUIRY
• NOTIFY
• REPLY
• REQUEST
• SENDER

Database performance and query optimization 853


Table 207. MESSAGE_QUEUE_INFO table function (continued)

Column Name Data Type Description

MESSAGE_SUBTYPE VARCHAR(22) Subtype of message.


The values returned for REPLY messages:
• FROM EXIT PROGRAM
• FROM SYSTEM REPLY LIST
• MESSAGE DEFAULT USED
• NOT VALIDITY CHECKED
• SYSTEM DEFAULT USED
• VALIDITY CHECKED
The value returned for some REQUEST messages:
• WITH PROMPTING
Contains the null value for other message types.

MESSAGE_TEXT VARGRAPHIC(1024) The first level text of the message including tokens, or the impromptu message
CCSID 1200 text.
Contains the null value if MESSAGE_TYPE is REPLY or if the message file could not
be accessed.

SEVERITY SMALLINT The severity assigned to the message.

MESSAGE_TIMESTAMP TIMESTAMP The timestamp when the message was sent.

MESSAGE_KEY BINARY(4) The key assigned to the message.


The key is assigned by the command or API that sends the message. For details,
see Message Types and Message Keys in the Qmhrcvm API

ASSOCIATED_MESSAGE_KEY BINARY(4) For MESSAGE_TYPE of REPLY, contains the associated inquiry or notify message
key.
Contains the null value for other message types.

FROM_USER VARCHAR(10) The current user of the thread when the message was sent.

FROM_JOB VARCHAR(28) The qualified job name of the job that sent the message.

FROM_PROGRAM VARCHAR(10) The program that sent the message.

MESSAGE_FILE_LIBRARY VARCHAR(10) The name of the library containing the message file.
Contains the null value if MESSAGE_ID is null or if the message file could not be
accessed.

MESSAGE_FILE_NAME VARCHAR(10) The message file containing the message.


Contains the null value if MESSAGE_ID is null.

MESSAGE_TOKENS VARCHAR(4096) FOR The message token string. If the value is longer than 4096 characters, it will be
BIT DATA truncated with no warning.
Contains the null value if there are no tokens.

MESSAGE_SECOND_LEVEL_TEXT VARGRAPHIC(4096) The second level text of the message including tokens.
CCSID 1200
Contains the null value if MESSAGE_ID is null or if the message has no second
level text or if the message file could not be accessed.

Example
• Return a list of inquiry messages in QSYSOPR that have not been replied to

SELECT MESSAGE_ID, MESSAGE_TEXT, MESSAGE_TIMESTAMP


FROM TABLE(QSYS2.MESSAGE_QUEUE_INFO(MESSAGE_FILTER => 'INQUIRY'));

854 IBM i: Performance and Query Optimization


MESSAGE_QUEUE_INFO view
The MESSAGE_QUEUE_INFO view returns one row for each message in a message queue. It returns
information similar to what is returned by the Display Messages (DSPMSG) CL command and the Receive
Nonprogram Message (QMHRCVM) API.
This view does not change the contents of the message queue. The message is kept in the message
queue without changing its new or old designation. The view does not utilize the wait time parameter as
described in the QMHRCVM API. A wait time of 0 is used.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the message queue, and
• *USE authority to the message queue
The following table describes the columns in the view. The system name is MSGQ_INFO. The schema is
QSYS2.
Table 208. MESSAGE_QUEUE_INFO view

Column Name System Column Name Data Type Description

MESSAGE_QUEUE_LIBRARY MSGQ_LIB VARCHAR(10) The name of the library containing the message queue.

MESSAGE_QUEUE_NAME MSGQ_NAME VARCHAR(10) The name of the message queue containing the message.

MESSAGE_ID MSGID VARCHAR(7) The message ID for this message.

Nullable Contains the null value if this is an impromptu message or


MESSAGE_TYPE is REPLY.

MESSAGE_TYPE MSG_TYPE VARCHAR(13) Type of message. Values are:


• COMPLETION
• DIAGNOSTIC
• ESCAPE
• INFORMATIONAL
• INQUIRY
• NOTIFY
• REPLY
• REQUEST
• SENDER

MESSAGE_SUBTYPE MSG_SUBTYP VARCHAR(22) Subtype of message.

Nullable The values returned for REPLY messages:


• FROM EXIT PROGRAM
• FROM SYSTEM REPLY LIST
• MESSAGE DEFAULT USED
• NOT VALIDITY CHECKED
• SYSTEM DEFAULT USED
• VALIDITY CHECKED
The value returned for some REQUEST messages:
• WITH PROMPTING
Contains the null value for other message types.

MESSAGE_TEXT MSG_TEXT VARGRAPHIC(102 The first level text of the message including tokens, or the
4) CCSID 1200 impromptu message text.

Nullable Contains the null value if the message file could not be accessed.

SEVERITY SEVERITY SMALLINT The severity assigned to the message.

MESSAGE_TIMESTAMP MSG_TIME TIMESTAMP The timestamp when the message was sent.

MESSAGE_KEY MSG_KEY BINARY(4) The key assigned to the message.


The key is assigned by the command or API that sends the
message. For details, see Message Types and Message Keys in
the Qmhrcvm API

Database performance and query optimization 855


Table 208. MESSAGE_QUEUE_INFO view (continued)

Column Name System Column Name Data Type Description

ASSOCIATED_MESSAGE_KEY ASSOC_KEY BINARY(4) For MESSAGE_TYPE of REPLY, contains the associated inquiry or
notify message key.
Nullable
Contains the null value for other message types.

FROM_USER FROM_USER VARCHAR(10) The current user of the thread when the message was sent.

FROM_JOB FROM_JOB VARCHAR(28) The qualified job name of the job that sent the message.

FROM_PROGRAM FROM_PGM VARCHAR(10) The program that sent the message.

MESSAGE_FILE_LIBRARY MSGF_LIB VARCHAR(10) The name of the library containing the message file.

Nullable Contains the null value if MESSAGE_ID is null or if the message


file could not be accessed.

MESSAGE_FILE_NAME MSGF_NAME VARCHAR(10) The message file containing the message.

Nullable Contains the null value if MESSAGE_ID is null.

MESSAGE_TOKENS MSG_TOKENS VARCHAR(4096) The message token string. If the value is longer than 4096
FOR BIT DATA characters, it will be truncated with no warning.
Nullable Contains the null value if there are no tokens.

MESSAGE_SECOND_LEVEL_TEXT MSG_TEXT2 VARGRAPHIC(409 The second level text of the message including tokens.
6) CCSID 1200
Contains the null value if MESSAGE_ID is null or if the message
Nullable has no second level text or if the message file could not be
accessed.

Example
• Examine all inquiry messages and their responses.

SELECT a.message_timestamp, a.message_text, a.from_user,


b.message_timestamp, b.message_text, b.from_user
FROM qsys2.message_queue_info a INNER JOIN qsys2.message_queue_info b
ON a.message_key = b.associated_message_key
WHERE a.message_type = 'INQUIRY' AND
b.message_type = 'REPLY'
ORDER BY b.message_timestamp DESC;

REPLY_INQUIRY_MESSAGES scalar function


The REPLY_INQUIRY_MESSAGES scalar function replies to one or more inquiry messages in the QSYSOPR
message queue.
This function extends what can be done by the Send Reply (SNDRPY) CL command.
Authorization: See Note below.

REPLY_INQUIRY_MESSAGES ( message_id
MESSAGE_ID =>

, search-message_text
SEARCH_MESSAGE_TEXT =>

, response
RESPONSE =>

)
, remove-message
REMOVE_MESSAGE =>

856 IBM i: Performance and Query Optimization


The schema is SYSTOOLS.

message-id A character string containing the message identifier of the inquiry message. The special
value *IMMED can be specified to indicate the message has no message identifier.
search- A character string containing a string that must exist in the message text in order for the
message-text inquiry message to be selected. The comparison is case insensitive.
When message-id is *IMMED, a value must be specified. Otherwise, a value is optional.
response A character string containing the response to be provided to any inquiry messages that
meet the message-id and search-string criteria.
If response is omitted or contains the value *DFT, the default reply stored in the message
description of the inquiry message is sent as the reply, or the system default reply of *N
is used.
remove- A character string that indicates whether the inquiry message and its reply are removed
message from the message queue.

NO The message will not be removed.


YES The message will be removed. This is the default.

The result of the function is an integer that indicates the number of inquiry messages that were
responded to.

Note
This function is provided in the SYSTOOLS schema as an example of how to respond to inquiry messages
in the QSYSOPR message queue using an SQL scalar function. Similar to other Db2 for i provided tools
within SYSTOOLS, the SQL source can be extracted and used as a model for building similar helper
functions, or to create a customized version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Examples
• Respond to any inquiry messages for message identifier CPA7025. Leave the messages in the message
queue.

VALUES SYSTOOLS.REPLY_INQUIRY_MESSAGES(
MESSAGE_ID => 'CPA7025',
RESPONSE => 'I',
REMOVE_MESSAGE => 'NO'
);

• Respond to any impromptu inquiry messages containing the text string 'restore'.

VALUES SYSTOOLS.REPLY_INQUIRY_MESSAGES(
MESSAGE_ID => '*IMMED'
SEARCH_MESSAGE_TEXT => 'restore',
RESPONSE => 'CONTINUE',
REMOVE_MESSAGE => 'YES'
);

REPLY_LIST_INFO view
The REPLY_LIST_INFO view contains information about the current job's reply list entries.
The information returned is similar to the detail available through the Work with Reply List Entries
(WRKRPYLE) CL command.
Authorization: None required.

Database performance and query optimization 857


The following table describes the columns in the view. The system name is REPLYLIST. The schema is
QSYS2.
Table 209. REPLY_LIST_INFO view

System Column
Column Name Name Data Type Description

SEQUENCE_NUMBER SEQNO SMALLINT The number that specifies the search order of the
entries in the reply list.

MESSAGE_ID MSGID VARCHAR(7) The identifier of the inquiry message for which
automatic system action is to be taken.
A value of ANY indicates that this reply list
entry matches any message identifier. Unless
comparison data is specified for this reply list
entry, all reply list entries with a sequence number
greater than this one are ignored.

MESSAGE_REPLY REPLY VARCHAR(32) When an inquiry message is received with a


matching message identifier, this value defines
whether an automatic reply to the message is
given.

DEFAULT The default reply to the inquiry


message is sent.

REQUIRED The inquiry message requires


an explicit reply.

character The character string to be sent


string as the reply to the inquiry
message.

COMPARISON_DATA COMPDATA VARGRAPHIC(28) CCSID The character string that is compared with the
1200 message data of the inquiry message.

Nullable Contains the null value if there is no comparison


data.

COMPARISON_DATA_OFFSET OFFSET SMALLINT The position in the message data of the inquiry
message at which the comparison with the
Nullable COMPARISON_DATA starts.
Contains the null value if there is no comparison
data.

DUMP_JOB DUMPJOB VARCHAR(3) Specifies whether the job that sent the inquiry
message is to be dumped.

NO The job is not dumped.

YES The job is dumped before control returns


to the program that is sending the
message.

Example
• See the reply list entries for your job

SELECT * FROM QSYS2.REPLY_LIST_INFO

SEND_MESSAGE procedure
The SEND_MESSAGE procedure sends an informational message to the QSYSOPR message queue.
Authorization: The caller must have:
• *OBJOPR and *ADD authorities to the QSYSOPR message queue,
• *EXECUTE authority to the library containing the message file, and
• *USE authority to the message file.

858 IBM i: Performance and Query Optimization


SEND_MESSAGE ( message-id
MESSAGE_ID =>

, message-length
MESSAGE_LENGTH =>

, message-text
MESSAGE_TEXT =>

, message-file-library
MESSAGE_FILE_LIBRARY =>

)
, message-file
MESSAGE_FILE =>

The schema is QSYS2.

message-id A character string expression that identifies the message ID to send to the
QSYSOPR message queue.
message-length An integer value that defines the length of message-text.
message-text The message text for the message.
message-file-library The library that contains message-file. Can contain the special value *LIBL. The
default is QSYS.
message-file The message file that contains message-id. The default is QSQLMSG.

Notes
This procedure is designed to send a predefined message to the QSYSOPR message queue. The message
is expected to have one substitution variable defined as *CHAR *VARY 2.
When sending a message from a Query Supervisor exit program, SQL7064 in the QSYS/QSQLMSG
message file is defined for this purpose. When sending a message in other situations, it is recommended
that a different message should be used.

Example
• Send a message to the QSYSOPR message queue when a critical error is diagnosed.

CALL QSYS2.SEND_MESSAGE('APP1234', 31, 'Unexpected error in MYLIB/PGM2.' ,


'APPLIB', 'MYMSGF');

Performance Services
These services provide information related to system performance.

COLLECTION_SERVICES_INFO view
The COLLECTION_SERVICES_INFO view returns the configuration properties for Collection Services.
The values returned for the columns in the view are closely related to the values returned by the
Configure Perf Collection (CFGPFRCOL) CL command and the Retrieve Collection Services Attributes
(QypsRtvColSrvAttributes) API.

Database performance and query optimization 859


Authorization: The caller must have *USE authority on the QSYS/QYPSCOLL service program or be
authorized through the QPMCCFCN authorization list.
The following table describes the columns in the view. The system name is CS_INFO. The schema is
QSYS2.
Table 210. COLLECTION_SERVICES_INFO view

System Column
Column Name Name Data Type Description

ACTIVE_COLLECTION_LIBRARY CURCOL_LIB VARCHAR(10) The name of the library where the currently active management
collection object is stored.
Nullable
Contains the null value if there is no active collection.

ACTIVE_COLLECTION_NAME CURCOL VARCHAR(10) The name of the current management collection object.

Nullable Contains the null value if there is no active collection.

ACTIVE_COLLECTION_PROFILE CURCOL_PRF VARCHAR(10) The name of the collection profile being used by the active collection.
The collection profile defines which categories of data to collect.
Nullable
*CUSTOM A profile where both the categories to collect and
category interval times may be customized.

*ENHCPCPLN Enhanced Capacity Planning. Same as *STANDARDP


plus the PEX Data - Processor Efficiency category.

*MINIMUM The minimum set of categories required to support


basic performance reporting functions.

*STANDARD All categories that are typically used for performance


reporting except for communications protocol related
data.

*STANDARDP Same as *STANDARD but communications protocol


categories are included.

Contains the null value if there is no active collection.

ACTIVE_COLLECTION_START_TIM START_TIME TIMESTAMP The UTC timestamp when the current (active) collection was started.
E
Nullable Contains the null value if there is no active collection.

COLLECTION_LIBRARY LIB VARCHAR(10) The name of the library where performance data is stored.

COLLECTION_PROFILE DFTCOLPRF VARCHAR(10) The name of the configured collection profile. The collection profile
defines which categories of data to collect.

*CUSTOM A profile where both the categories to collect and


category interval times may be customized.

*ENHCPCPLN Enhanced Capacity Planning. Same as *STANDARDP


plus the PEX Data - Processor Efficiency category.

*MINIMUM The minimum set of categories required to support


basic performance reporting functions.

*STANDARD All categories that are typically used for performance


reporting except for communications protocol related
data.

*STANDARDP Same as *STANDARD but communications protocol


categories are included.

DEFAULT_COLLECTION_INTERVAL INTERVAL INTEGER The default interval, in seconds, used when collecting data for a
category.
Nullable
Values are: 15, 30, 60, 300, 900, 1800, or 3600 seconds.
Contains the null value if not collecting on an interval.

MGTCOL_RETENTION_PERIOD RETPERIOD INTEGER The management collection (*MGTCOL) object retention period., in
hours. *MGTCOL objects in the configured collection library that
Nullable are older than the retention period are automatically deleted when
Collection Services is started or cycled.
Contains the null value for permanent retention.

CYCLE_TIME CYCTIME INTEGER The number of minutes past midnight when the first cycle is to occur.
The maximum value is 1439 minutes (which is one minute less than 24
hours).

CYCLE_INTERVAL CYCITV INTEGER The number of hours between cycles. The cycle time can range from a
minimum value of one hour to a maximum value of 24 hours.

860 IBM i: Performance and Query Optimization


Table 210. COLLECTION_SERVICES_INFO view (continued)

System Column
Column Name Name Data Type Description

CREATE_STANDARD_DB_FILES CRTDBF VARCHAR(3) Whether the standard database file collection is created by Collection
Services while performance data is being collected.

NO Collection Services will not create the standard database file


collection.

YES Collection Services will create the standard database file


collection. A batch job named CRTPFRDTA is submitted to
process the data in the current management collection object
as it is collected. The collection name (begins with a "Q") is the
same as the name of the *MGTCOL the data was exported from.

RETENTION_DAYS STDDTARET INTEGER This retention period, in days, used to determine how long standard
database file collections should be retained on the system. When
Nullable Collection Services is started or cycled, the Collection Services server
job (QYPSPFRCOL) will automatically delete standard database file
collections in the configured collection library that are older than the
current retention period.
Contains the null value for permanent retention.

CREATE_SUMMARY_DB_FILES CRTPFRSUM VARCHAR(3) Whether additional logical files are created as supported by the
CRTPFRSUM command.

NO Summary file data is not generated.

YES Summary file data is generated.

CREATE_SYSTEM_MONITOR_ CRTSYSMON VARCHAR(3) Whether additional system monitor database files should be created by
DB_FILES Collection Services while performance data is being collected.

NO Collection Services will not create the system monitor database


files for the standard database file collection.

YES Collection Services will create the system monitor database


files for the standard database file collection. The batch job
named CRTPFRDTA will populate the system monitor database
files using the data in the current management collection object
as it is collected.

ENABLE_SYSTEM_MONITORING ENBSYSMON VARCHAR(3) Whether Collection Services is configured to collect and produce data
for system monitors.

NO System monitor support is not enabled.

YES System monitor support is enabled. Collection Services will


collect certain data categories more frequently than the
configured default collection interval. A batch job named
CRTPFRDTA2 is submitted to produce a system monitor
database file collection with the same name as the
management collection object except it begins with an 'R'.

SYSTEM_MONITOR_ SYSMONRET INTEGER This retention period, in days, used to determine how long system
DB_FILE_RETENTION monitor database file collections should be retained on the system.
Nullable When Collection Services is started or cycled, the Collection Services
server job (QYPSPFRCOL) will automatically delete system monitor
database file collections in the configured collection library that are
older than the retention period.
Contains the null value for permanent retention.

CATEGORY_LIST_COUNT CGY_COUNT INTEGER The number of entries in CATEGORY_LIST.

CATEGORY_LIST SYSMONCGY VARCHAR(2000) A list of collection categories that are included in the system monitor
collection. Each category can have an independent collection interval.
CCSID 1208 This list is returned as an array within a JSON object.
Nullable
Each entry in the JSON array contains two JSON objects:
• An object with a name of "category" and a value of the category name
• An object with a name of "interval" and a value of the category's
collection interval, in seconds
Contains the null value if CATEGORY_LIST_COUNT is 0.

EXCLUDED_LINE_COUNT EXC_COUNT INTEGER The number of entries in EXCLUDED_LINE_LIST.

Database performance and query optimization 861


Table 210. COLLECTION_SERVICES_INFO view (continued)

System Column
Column Name Name Data Type Description

EXCLUDED_LINE_LIST EXC_LIST VARCHAR(598) A list of communication line names that are excluded from the
calculation of communication line protocol metrics. Each entry is ten
Nullable characters long with a comma and space separating entries.
Contains the null value if EXCLUDED_LINE_COUNT is 0.

CREATE_HISTORICAL_DATA CRTPFRHST VARCHAR(3) Whether historical data will be created when Collection Services is
cycled.

NO Collection Services will not create historical data.

YES Collection Services will create historical data by processing


management collection objects that exist in the configured
collection library. A batch job named QYPSPFRHST is submitted
by Collection Services at cycle time.

HISTORICAL_DATA_INTERVAL HSTITV INTEGER The time interval, in seconds, used to create historical data.

HISTORICAL_SUMMARY_DATA_ HSTSUMRET INTEGER The historical summary data retention period, in months, that
RETENTION determines how long Collection Services historical summary data is
to exist. Historical summary data is stored in files beginning with
QAPMHMxxxx. Historical summary data older than the retention period
is deleted.

CREATE_HISTORICAL_DETAILED_ CRTHSTDTL VARCHAR(3) Whether historical detailed data will be created when Collection
DATA Services is cycled. Creating historical detailed data will allow detailed
data for the top contributors of various metrics to be stored in the
historical collection to be used as drill-down data. The number of top
contributors is determined by the value of the historical detailed data
filter.

NO Collection Services will not create historical detailed data.

YES Collection Services will create historical detailed data when


processing management collection objects that exist in the
configured collection library. A batch job named QYPSPFRHST
is submitted by Collection Services at cycle time.

HISTORICAL_DETAILED_DATA_ HSTDTLRET INTEGER The historical detailed data retention period, in days, that determines
RETENTION how long Collection Services historical detailed data is to exist.
Historical detailed data is stored in files beginning with QAPMHDxxxx.
Historical detailed data older than the retention period is deleted.

HISTORICAL_DETAILED_DATA_ HSTFILTER INTEGER The number of top contributors for each metric to be stored in the
FILTER historical data collection to be used as detailed drill-down data.
Nullable
Contains the null value if all detailed data is kept.

Example
• Return the Collection Services configuration properties.

SELECT * FROM QSYS2.COLLECTION_SERVICES_INFO;

PowerHA Services
These table functions and views provide information about PowerHA.
PowerHA SQL Services

Product Services
These services provide information about licensed products.

862 IBM i: Performance and Query Optimization


CHECK_PRODUCT_OPTIONS table function
The CHECK_PRODUCT_OPTIONS table function reports differences between the correct structure and the
actual structure of all installed software products.
This service combines the QSYS2.SOFTWARE_PRODUCT_INFO view and the Check Product Option
(CHKPRDOPT) CL command to check all the installed products and options on the system.
Authorization: See Note below.

CHECK_PRODUCT_OPTIONS (
check-signature
CHECK_SIGNATURE =>

The schema is SYSTOOLS.

check- An expression that indicates whether the digital signatures of objects are to be checked.
signature
*ALL All objects that can be digitally signed will have the signature verified. Any
object that can be signed but has no signature will be identified in a message
but the product will not be set to be in error. Any signed object with a signature
that is not valid will be identified in a message. If an invalid signature is found,
the product will be set to be in an erroneous state.
*NONE Digital signatures of objects will not be checked.
*SIGNED Objects with digital signatures are checked. Any object that has been signed
will have the signature verified. Objects with invalid signatures will be identified
in a message and the product will be set to be in an erroneous state. This is the
default.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 211. CHECK_PRODUCT_OPTIONS table function

Column Name Data Type Description

PRODUCT_ID VARCHAR(7) The product ID.

PRODUCT_OPTION VARCHAR(5) The product option of the product. Can contain the following special
value:

*BASE The base part of the product.

LOAD_ID VARCHAR(4) The load ID of the product load .

RELEASE_LEVEL VARCHAR(10) The release level of the product.

CHECK_SUCCESSFUL VARCHAR(3) Whether the check was successful.

NO A message was returned for this product option.

YES No message was returned for this product option.

FAILURE_MESSAGE_ID CHAR(7) The message ID of the failure when CHECK_SUCCESSFUL has a value
of NO.
Examine the job log for additional message details. The CL command
listed in the CHKPRDOPT_COMMAND column can be used to run the
check again.
Contains the null value if CHECK_SUCCESSFUL is YES.

FAILURE_MESSAGE_TEXT VARGRAPHIC(1024) The message text for the failure when CHECK_SUCCESSFUL has a
value of NO.
CCSID 1200
Contains the null value if CHECK_SUCCESSFUL is YES.

CHKPRDOPT_COMMAND VARCHAR(1000) The CL command string used to check this product option.

Database performance and query optimization 863


Note
This function is provided in the SYSTOOLS schema as an example of how to return information that has
been written to the joblog. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can
be extracted and used as a model for building similar helper functions, or to create a customized version
within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
• List any potential problems with all installed software products.

SELECT * FROM TABLE(SYSTOOLS.CHECK_PRODUCT_OPTIONS( ));

LICENSE_EXPIRATION_CHECK procedure
The LICENSE_EXPIRATION_CHECK procedure sends a message to the QSYSOPR message queue for
every license that corresponds to an installed product that has already expired or is set to expire within
the specified number of days.
Authorization: See Note below.

LICENSE_EXPIRATION_CHECK (

)
expiration-interval
EXPIRATION_INTERVAL =>

The schema is SYSTOOLS.

expiration- An integer value that indicates the number of days to use as the threshold for
interval checking license information. If not specified, 30 will be used.

Note
This procedure is provided in the SYSTOOLS schema as an example of how to work with license
information using an SQL procedure. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL
source can be extracted and used as a model for building similar procedures, or to create a customized
version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
• Send an informational message to the system operator message queue, QSYS/QSYSOPR, for every
installed product with a license that will expire in the next 10 days.

CALL SYSTOOLS.LICENSE_EXPIRATION_CHECK(10);

864 IBM i: Performance and Query Optimization


LICENSE_INFO view
The LICENSE_INFO view contains information about all products or features that contain license
information.
The values returned for the columns in the view are similar to the values returned by the Work with
License Information (WRKLICINF) CL command or Retrieve License Information (QLZARTV) API. Refer to
the API for more detailed information.
Authorization: None required.
The following table describes the columns in the view. The system name is LIC_INFO. The schema is
QSYS2.
Table 212. LICENSE_INFO view

Column Name System Column Name Data Type Description

PRODUCT_ID LICPGM VARCHAR(7) The identifier of the product.

LICENSE_TERM LIC_TERM VARCHAR(6) The license term indicates whether the authorized usage limit
for a product exists until the next version, next release, or next
modification level of the product.
• Vx or vv for products licensed by version.
• VxRy or vvrr for products licensed by release.
• VxRyMz or vvrrmm for products licensed by modification.

RELEASE_LEVEL RLS_LVL VARCHAR(6) The version, release, and modification level of the product in either
VxRyMz or vvrrmm format.

FEATURE_ID FEATURE VARCHAR(4) The feature number of the product.

INSTALLED INSTALLED VARCHAR(3) Indicates whether this feature number of the product is installed.

NO The feature is not installed.

YES The feature is installed.

PROCESSOR_GROUP PROC_GROUP VARCHAR(3) The processor group of this system.

PRODUCT_TEXT LABEL VARGRAPHIC(50) The description of the product or feature.


CCSID 1200
Contains null if there is no description text.
Nullable

USAGE_LIMIT USG_LIMIT INTEGER The usage limit of the product or feature that contains license
information. Values are 0-999999 indicating the number of users
Nullable allowed to access the product.
Contains null if there is no usage limit.

USAGE_LIMIT_UPDATED USG_UPDATE TIMESTAMP(0) The timestamp when the usage limit was last updated.
Nullable Contains null if the usage limit has never been updated.

USAGE_TYPE USAGE_TYPE VARCHAR(11) The usage type of the license.

*CONCURRENT The usage type is concurrent, meaning the


usage limit is for the number of uses held by
unique jobs using the product or feature at the
same time.

*REGISTERED The usage type is registered, meaning the


usage limit is for the number of uses held by
license users registered to use the product or
feature.

*PROCESSOR The usage type is processor, meaning the


usage limit is for the number of processors on
system partitions where this product or feature
is in use.

USAGE_COUNT USG_COUNT DECIMAL(8,2) The current usage count for the product or feature. Valid values are
0 through 999999. If the product is using processor usage type, the
usage count value is rounded up to the next whole number.

GLOBAL_COUNT GLOB_COUNT DECIMAL(8,2) The number of jobs currently using this product or feature across
all system partitions.

LICENSED_USER_COUNT LIC_COUNT INTEGER The number of current license users.

Database performance and query optimization 865


Table 212. LICENSE_INFO view (continued)

Column Name System Column Name Data Type Description

THRESHOLD THRESHOLD DECIMAL(10,2) The usage limit threshold for this product or feature.

Nullable Contains null if there is no usage limit threshold.

PEAK_USAGE PEAK_USAGE DECIMAL(10,2) For concurrent usage, the maximum number of uses held by
license users of the product or feature at one time.
For registered usage, the maximum number of uses that have been
registered through license users for the product or feature.
For processor usage, the maximum number of processors
configured for this system partition while this product or feature
was in use.

LAST_PEAK LAST_PEAK TIMESTAMP(0) The timestamp when the peak usage of the product or feature last
occurred since the peak usage was reset to zero.
Nullable
Contains null if the product has not been used since the peak usage
was reset to zero.

COMPLIANCE_TYPE COMP_TYPE VARCHAR(10) The compliance type of the program determines the action taken
when the usage limit of the product or feature is exceeded.

*OPRACTION License requests are denied and failure


messages are sent.

*WARNING A warning message is sent.

*KEYED Requests for licenses over the usage limit are


allowed for the number of days in the product's
grace period. Once the grace period ends, the
license users holding uses over the usage limit
will be released and no requests for uses over
the limit will be granted until a new license
key is received from the software provider. The
expiration date is the date the license will expire.
After the expiration date is reached, the default
usage limit is in effect. When a request for a
license is received after the usage limit has been
reached, the system sends a warning message
to the system operator message queue and to
any additional message queues defined for the
product.

LOG_VIOLATION LOG VARCHAR(3) Specifies whether or not requests exceeding the usage limit are
logged in the QUSRSYS/QLZALOG journal.

NO The requests for a license when the usage count is greater


than or equal to the usage limit will not be logged.

YES The requests for a license when the usage count is greater
than or equal to the usage limit will be logged.

LICENSE_EXPIRATION EXPIR_DATE DATE The date the license will expire. After the expiration date is
reached, the usage limit is reset to the default usage limit.
Nullable
Contains null if the license has no expiration date.

GRACE_PERIOD GRACE_PRD INTEGER The number of days a user has to obtain a new license key after a
product or feature exceeds its usage limit.

GRACE_END GRACE_END DATE The date the grace period expires. When a request for license uses
exceeds the usage limit for a product or feature, the date the grace
Nullable period expires is determined by adding the number of days in the
grace period to the current date.
Contains null if there is no grace period or the grace period has
expired.

VENDOR_DATA VENDOR VARCHAR(8) Information the vendor defined when the key was added using the
Add License Key Information (ADDLICKEY) command.

866 IBM i: Performance and Query Optimization


Table 212. LICENSE_INFO view (continued)

Column Name System Column Name Data Type Description

MESSAGE_QUEUE1 MESSAGE_1 VARCHAR(10) The name of the first message queue to which messages will be
sent.
Nullable
Each of these message queues, in addition to the system operator
message queue, will be sent a messages if one of the following
occurs:
• The usage count threshold is met.
• A license request is made, and the usage count is equal to or
greater than the usage limit.
• The usage limit is changed.
The messages sent include:
• CPI9E10 - License usage limit changed for product &1.
• CPI9E19 - Usage limit threshold exceeded.
• CPI9E75 - Grace period will expire on &3.
• CPI9E76 - Expiration date will be reached on &3.
Contains null if there is no first message queue.

MESSAGE_QUEUE_LIBRARY1 LIBRARY_1 VARCHAR(10) The library containing the first message queue.

Nullable Contains null if there is no first message queue.

MESSAGE_QUEUE2 MESSAGE_2 VARCHAR(10) The name of the second message queue to which messages will be
sent.
Nullable
Contains null if there is no second message queue.

MESSAGE_QUEUE_LIBRARY2 LIBRARY_2 VARCHAR(10) The library containing the second message queue.

Nullable Contains null if there is no second message queue.

MESSAGE_QUEUE3 MESSAGE_3 VARCHAR(10) The name of the third message queue to which messages will be
sent.
Nullable
Contains null if there is no third message queue.

MESSAGE_QUEUE_LIBRARY3 LIBRARY_3 VARCHAR(10) The library containing the third message queue.

Nullable Contains null if there is no third message queue.

MESSAGE_QUEUE4 MESSAGE_4 VARCHAR(10) The name of the fourth message queue to which messages will be
sent.
Nullable
Contains null if there is no fourth message queue.

MESSAGE_QUEUE_LIBRARY4 LIBRARY_4 VARCHAR(10) The library containing the fourth message queue.

Nullable Contains null if there is no fourth message queue.

MESSAGE_QUEUE5 MESSAGE_5 VARCHAR(10) The name of the fifth message queue to which messages will be
sent.
Nullable
Contains null if there is no fifth message queue.

MESSAGE_QUEUE_LIBRARY5 LIBRARY_5 VARCHAR(10) The library containing the fifth message queue.

Nullable Contains null if there is no fifth message queue.

Example
Return information about all licensed products and features that will expire within the next 2 weeks.

SELECT * FROM QSYS2.LICENSE_INFO


WHERE LICENSE_EXPIRATION <= CURRENT DATE + 14 DAYS;

SOFTWARE_PRODUCT_INFO view
The SOFTWARE_PRODUCT_INFO view returns information about software products.
The values returned for the columns in the view are closely related to the values returned by the Display
Software Resources (DSPSFWRSC) command and the Retrieve Product Information (QSZRTVPR) API.
Authorization: None required.

Database performance and query optimization 867


The following table describes the columns in the view. The system name is SFW_PROD. The schema is
QSYS2.
Table 213. SOFTWARE_PRODUCT_INFO view

Column Name System Column Name Data Type Description

PRODUCT_ID PRODUCT_ID VARCHAR(7) The product ID.

PRODUCT_OPTION PROD_OPT VARCHAR(5) The product option of the product. Can contain
the following special value:

*BASE The base part of the product.

LOAD_ID LOAD_ID VARCHAR(4) The load ID of the product load for which
information was returned.

LOAD_TYPE LOAD_TYPE VARCHAR(8) The type of load.

CODE The load is a code load.

LANGUAGE The load is a language load.

RELEASE_LEVEL RELEASE VARCHAR(10) The release level of the product selected.

INSTALLED INSTALLED VARCHAR(3) Whether the code load for this product option
is installed. A load is installed if a product
load (*PRDLOD) object is loaded on the system
by the Restore Licensed Program (RSTLICPGM)
command.

NO The code load for this product option is


not installed.

YES The code load for this product option is


installed.

SYMBOLIC_LOAD_STATE SYM_STATE VARCHAR(9) The symbolic state of the load for which
information was returned. This value, in
conjunction with the LOAD_ERROR column, can
be used to determine if the load is installed
correctly.

CREATED The product load object for this


load exists.

DAMAGED If this is for an option other


than the base option or for a
language load for the base option,
the product load object has been
damaged. If this is for the code
load for the base option, one of
the following happened:
• The product definition for this
product ID and release level
has been damaged.
• The product load object has
been damaged.

DEFINED The load is defined. The product


load object for this load does not
exist.

INSTALLED The product load (*PRDLOD)


object for this load was
loaded onto the system by the
RSTLICPGM command.

LOADED Indicates one of the following:


• A restore licensed program
function is in progress.
• A delete licensed program
function is in progress.

PACKAGED The product load object for this


load has been packaged with the
PKGPRDOPT command.

868 IBM i: Performance and Query Optimization


Table 213. SOFTWARE_PRODUCT_INFO view (continued)

Column Name System Column Name Data Type Description

LOAD_ERROR LOAD_ERROR VARCHAR(3) Whether there is a known error for this load.

NO No error was found the last time that


the state of this load was checked or
updated.

YES An error was found the last time that


the state of this load was checked or
updated.

LOAD_STATE LOAD_STATE CHAR(2) The state of the load for which information was
returned.

10 The load is defined.

20 The product load object for this load exists.

30 The product load object for this load


has been packaged with the PKGPRDOPT
command or the QSZPKGPO API.

32 The product load object for this load


has been packaged with the PKGPRDOPT
command or the QSZPKGPO API. Either
a development library or folder was
renamed, but the product does not allow
dynamic naming, or the product definition
or product load for a packaged load was
renamed or moved to another library.

33 The product load object for this load


has been packaged with the PKGPRDOPT
command or the QSZPKGPO API. However,
an object was found to be damaged the
last time that the CHKPRDOPT command
or SAVLICPGM command was used for this
load.

34 The product load object for this load


has been packaged with the PKGPRDOPT
command or the QSZPKGPO API. Either an
attempt was made to delete the product
load using the delete licensed program
function and the function failed, or a
packaged object was missing the last
time that the CHKPRDOPT command or
SAVLICPGM command was used for this
load.

35 A RSTLICPGM command is in progress.


The product being replaced had been
packaged, but not installed.

38 A DLTLICPGM command is in progress. The


product being deleted had been packaged,
but not installed.

3E A RSTLICPGM command did not complete


successfully. A preoperation exit program
failed. The product being replaced had
been packaged, but not installed.

3F A RSTLICPGM command failed. A


preoperation exit program did not fail.
The product being replaced had been
packaged, but not installed.

50 A RSTLICPGM command is in progress. The


product being replaced had been installed.

53 A DLTLICPGM command is in progress. The


product being deleted had been installed.

59 This product is an IBM-supplied product,


and it is not compatible with the currently
installed release level of the operating
system.

Database performance and query optimization 869


Table 213. SOFTWARE_PRODUCT_INFO view (continued)

Column Name System Column Name Data Type Description

LOAD_STATE (continued)
60 The product load object for this load was
loaded onto the system by the RSTLICPGM
command.

61 The product load object for this load


was loaded onto the system by the
RSTLICPGM command, but a postoperation
exit program failed.

62 An installed library or folder was renamed,


but the product does not allow dynamic
naming.

63 The product load object for this load was


installed by the RSTLICPGM command, but
an object is damaged.

64 The product load object for this load was


installed by the RSTLICPGM command, but
an object was found to be missing when
CHKPRDOPT or SAVLICPGM was used, or
an error occurred while DLTLICPGM was
being used.

67 The CHKPRDOPT command was used for


this product load, but the postoperation
exit program failed or indicated that an
error was found.

6E A RSTLICPGM command did not complete


successfully.

6F A RSTLICPGM command failed.

90 The product load was installed


successfully. If an object was missing
or was damaged, and the problem
was corrected, using the CHKPRDOPT
command sets the state back to 90.

SUPPORTED SUPPORTED VARCHAR(3) Whether this load is currently supported. A


load can be supported by using the Work with
Supported Products (WRKSPTPRD) command in
the System Manager for IBM i licensed program.

NO This load is not currently supported.

YES This load is currently supported.

COMPATIBLE COMPATIBLE VARCHAR(3) Indicates whether this IBM product is compatible


with the current release.
Nullable
NO The product is not compatible.

YES The product is compatible.

Contains the null value if this product does not


have a compatibility value.

PRODUCT_LIBRARY_COUNT LIB_COUNT INTEGER The number of product libraries included in the


PRODUCT_LIBRARIES column.

PRODUCT_LIBRARIES PROD_LIB VARCHAR(120) The list of product load libraries. Each library
name entry is ten characters long with one blank
Nullable separating entries.
Contains the null value if
PRODUCT_LIBRARY_COUNT is 0.

PRODUCT_DIRECTORY_COUNT DIR_COUNT INTEGER The number of product directories included in the


PRODUCT_DIRECTORIES column.

PRODUCT_DIRECTORIES PROD_DIR DBCLOB(5M) CCSID 1200 The list of product directories. Directory entries
are separated by the string ' -- ' (a blank, two
Nullable minus signs, and a blank).
Contains the null value if
PRODUCT_DIRECTORY_COUNT is 0.

870 IBM i: Performance and Query Optimization


Table 213. SOFTWARE_PRODUCT_INFO view (continued)

Column Name System Column Name Data Type Description

TEXT_DESCRIPTION TEXT VARCHAR(132) Text description for this product option.

Nullable Contains the null value if there is no text


description or the text description is not available.

PRIMARY_LANGUAGE_LOAD_ID LANG_ID CHAR(4) For code loads, this field contains the primary
language of the product option.
Nullable
Contains the null value for language loads and for
code loads when no language is installed in the
libraries for the code load.

RELEASE_DATE REL_DATE DATE Indicates the value specified for the release date
when the product definition for this product load
Nullable was created.
Contains the null value if no release date was
specified.

MINIMUM_TARGET_RELEASE MIN_TGTRLS CHAR(6) The minimum release of the operating system to


which the Save Licensed Program (SAVLICPGM)
command will allow the product to be saved.

MINIMUM_VRM_BASE MIN_BASE CHAR(6) The minimum release level that is allowed for the
*BASE option that will run with the current level
Nullable of the option for the product. Can containing the
following special value:

*MATCH The release of the option matches


that of the *BASE.

Contains the null value for Licensed Internal


Code.

REQUIREMENTS_MET REQ_MET INTEGER The reason why the release requirements


between the base and option may or may not be
in error.

0 There is not enough information available to


determine if the release requirements have
been met. This value if always returned for a
load type of *LANG.

1 The releases of the *BASE and option meet


all requirements.

2 The release of the option is too old


compared to the *BASE.

3 The release of the *BASE is too old


compared to the option.

MIXED_RELEASES MIXED_REL VARCHAR(3) Product allows mixed releases.

NO The *BASE option and other options of


this product cannot be at different release
levels.

YES The *BASE option and other options of


this product can be at different release
levels.

LEVEL_ID LEVEL_ID CHAR(3) The level identifier of the product for which
information was returned. The format is Lxx.
Nullable
Contains the null value for all products other than
the operating system and Licensed Internal Code.

REGISTRATION_TYPE REG_TYPE CHAR(2) The registration type associated with the product.
The registration type and registration value
together make up the registration ID for the
product.

REGISTRATION_VALUE REG_VALUE VARCHAR(14) The registration value associated with the


product.

Example
• List any licensed programs that are in an error state.

Database performance and query optimization 871


SELECT *
FROM QSYS2.SOFTWARE_PRODUCT_INFO
WHERE LOAD_ERROR = 'YES';

PTF Services
These views provide PTF information.

DEFECTIVE_PTF_CURRENCY view
The DEFECTIVE_PTF_CURRENCY is a view which returns a list of defective PTFs on the system that do not
have the corrective PTF applied.
The data returned by this view is the same data that is returned by GO QMGTOOLS/MG option 24 (PTF
Menu), then taking option 3 (Compare DEFECTIVE PTFs from IBM). This information is generally refreshed
one time each week.
Authorization: See Note below.
The following table describes the columns in the view. The system name is DEFPTF_CUR. The schema is
SYSTOOLS.
Table 214. DEFECTIVE_PTF_CURRENCY view

Column name System column name Data type Description

PARTITION_NAME PART_NAME VARGRAPHIC(255) CCSID The name of the partition as it is known to the HMC.
1200

HOST_NAME HOST_NAME VARCHAR(256) Name of the system.

SERIAL_NUMBER SERIAL CHAR(8) The machine serial number.

OS_RELEASE_LEVEL OS_RELEASE VARCHAR(10) The operating system release level in VxRxMx


format.

DEFECTIVE_PTF DEF_PTF CHAR(7) The PTF identifier of the defective PTF.

APAR_ID APAR_ID CHAR(7) The APAR associated with the fixing PTF.

PRODUCT_ID LICPGM CHAR(7) The product ID.

FIXING_PTF FIXING_PTF CHAR(7) The PTF identifier of the corrective PTF. Returns the
value UNKNOWN if the corrective PTF cannot be
determined.

Note
This view is provided in the SYSTOOLS schema as an example of how to retrieve live data from a
service using SQL. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can be
extracted and used as a model for building similar interfaces, or to create a customized version within a
user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
List any defective PTFs on the current system that have not had the corrective PTF installed.

SELECT * FROM SYSTOOLS.DEFECTIVE_PTF_CURRENCY;

872 IBM i: Performance and Query Optimization


ELECTRONIC_SERVICE_AGENT_INFO view
The ELECTRONIC_SERVICE_AGENT_INFO view returns detailed information about the Electronic Service
Agent (ESA) connections.
The Electronic Service Agent must be configured and activated before this view can successfully return
results. See Electronic Service Agent for information about ESA.
The values returned for the columns in the view are closely related to the detail generated by the
VFYSRVAGT TYPE(*DETAIL) CL command.
When the ESA_CONNECTION column contains the null value, there is no connectivity.
RESULT_BY_IP_ADDRESS and RESULT_BY_HOSTNAME will both return a value of FAILURE, and partial
information will be returned in the other columns.
Authorization: The caller must have *ALLOBJ special authority.
The following table describes the columns in the view. The system name is ESA_INFO. The schema is
QSYS2.
Table 215. ELECTRONIC_SERVICE_AGENT_INFO view

Column Name System Column Name Data Type Description

ESA_STATUS STATUS VARCHAR(9) The ESA status.

ACTIVATED ESA has been activated on this


system

INACTIVE ESA has not been activated

ESA_CONNECTION CONNECTION VARCHAR(18) The type of connection between the IBM i and
IBM support servers.
Nullable
DIRECT LAN A direct LAN connection is
CONNECT configured

HTTP PROXY A connection through


an HTTP/HTTPS proxy is
configured

Contains the null value if the type of connection is


not available.

PROXY_HOST_OR_IP PROXY_HOST VARCHAR(256) The proxy hostname or proxy IP address,


depending on the configuration.
Nullable
Contains the null value if ESA_CONNECTION is
DIRECT LAN CONNECT.

PROXY_PORT PROXY_PORT INTEGER The proxy port.


Nullable Contains the null value if ESA_CONNECTIVITY is
DIRECT LAN CONNECT.

PROXY_ID PROXY_ID VARCHAR(16) The proxy user ID.

Nullable Contains the null value if the HTTP proxy is a non-


authenticated HTTP proxy, if the proxy ID is not
configured, or if ESA_CONNECTIVITY is DIRECT
LAN CONNECT.

RESULT_BY_IP_ADDRESS RESULT_IP VARCHAR(7) Connection status using IP address.

SUCCESS Returned successful status

FAILURE Returned failure status

UNKNOWN No response

If either RESULT_BY_IP_ADDRESS or
RESULT_BY_HOSTNAME has a value of SUCCESS,
ESA has a working connection.

Database performance and query optimization 873


Table 215. ELECTRONIC_SERVICE_AGENT_INFO view (continued)

Column Name System Column Name Data Type Description

RESULT_BY_HOSTNAME RESULT_HST VARCHAR(7) Connection status using hostname.

SUCCESS Returned successful status

FAILURE Returned failure status

UNKNOWN No response

If either RESULT_BY_IP_ADDRESS or
RESULT_BY_HOSTNAME has a value of SUCCESS,
ESA has a working connection.

SERVER_TYPE SERV_TYPE VARCHAR(25) The type of IBM support server.


The following values are returned when using
traditional path (Non-Edge) support. If using
simplified path (Edge), the values are prefixed
with EDGE. For example, EDGE BULK DATA.
Appended at the end of the value is a blank
followed by a number to make the value unique.

BULK DATA Handles bulk data


requests

CONFIGURATION Handles service


provider configuration
requests

FIX REPOSITORY Handles fix requests

GATEWAY Distributes requests


to the corresponding
servers

INVENTORY REPORT Handles inventory


report requests

PROBLEM REPORT Handles problem call


home requests

PROFILE Handles profile create/


edit/delete requests

STATUS REPORT Handles status requests

UPDATE ORDER Handles PTF download


requests

SERVER_HOSTNAME SERV_HOST VARCHAR(30) The hostname of the server. When


using Edge, SERVER_HOSTNAME will be
ESUPPORT.IBM.COM.

SERVER_IP_ADDRESS SERV_IP VARCHAR(45) The IP address of the server.

SERVER_PORT SERV_PORT INTEGER The port of the server. The default port is 443.

Example
• Return the connection information for the Electronic Service Agent.

SELECT * FROM QSYS2.ELECTRONIC_SERVICE_AGENT_INFO;

FIRMWARE_CURRENCY view
The FIRMWARE_CURRENCY view implements a live comparison of the firmware fix level installed on the
partition against the level available through a feed from the Fix Level Recommendation Tool (FLRT).
When queried, the view uses Display Hardware Resources (DSPHDWRSC) and Display Firmware Status
(DSPFMWSTS) commands and the JSON_TABLE and HTTPGETCLOB functions to consume a live JSON
feed from the Fix Level Recommendation Tool. When querying this view, the job CCSID cannot be 65535
or the query will fail.

874 IBM i: Performance and Query Optimization


The result of the query shows the firmware fix level installed on the partition and the firmware latest
fix levels made available by IBM. It also returns the general information shown by the DSPFMWSTS
command.
Authorization: See Note below.
The following table describes the columns in the view. The system name is FWCUR. The schema is
SYSTOOLS.
Table 216. FIRMWARE_CURRENCY view

Column name System column name Data type Description

FW_CURRENCY FW_CRNCY VARCHAR(28) A description of the firmware status. Values


returned are:

INSTALLED LEVEL The firmware fix level


IS CURRENT installed matches the most
current available from IBM

UPDATE An update is available from


AVAILABLE IBM

UPGRADE An upgrade is available from


AVAILABLE IBM

UPDATE AND Both an update and an


UPGRADE upgrade are available from
AVAILABLE IBM

FW_CURRENT_FIXPACK FW_FIXPACK VARCHAR(20) The current fix level on the partition.

FW_RELEASE_DATE FW_GA DATE The general availability date of the firmware on the
partition.

FW_MACHINE_TYPE_MODEL FW_MTM VARCHAR(20) The machine type model of the partition.

FW_RECOMMENDED_UPDATE FW_RUPD VARCHAR(20) The update fix level of the firmware.

Nullable Contains the null value if no update version is


available.

FW_RECOMMENDED_UPGRADE FW_RUPG VARCHAR(20) The upgrade fix level of the firmware.

Nullable Contains the null value if no upgrade version is


available.

FW_UPDATE_ACCESS_KEY_ KEY_EXP DATE The expiration date of the Update access key. Server
EXPIRATION firmware fix packs with a later date are not activated
Nullable until a valid Update access key expiration date is
detected.
Contains the null value if the update access key
expiration date is not available.

FW_SERVICE_PARITITON SVC_PART VARCHAR(3) Indicates whether the logical partition is operating


as a service partition.

NO The logical partition is not operating as a


service partition.

YES The logical partition is operating as a service


partition.

FW_UPDATE_POLICY UPD_POLICY VARCHAR(5) Indicates how changes are made to the server
firmware.

HMC The server firmware is managed by a


Hardware Management Console (HMC).
The operating system is not allowed to
make changes to the server firmware.

OPSYS The server firmware is managed


by the operating system using
Program Temporary Fixes (PTFs)
for the specified server firmware
product ID/release (FW_PRODUCT_ID
and FW_PRODUCT_RELEASE).

Database performance and query optimization 875


Table 216. FIRMWARE_CURRENCY view (continued)

Column name System column name Data type Description

FW_IPL_SOURCE IPL_SRC VARCHAR(9) The copy of the server firmware that was used on
the previous server IPL.

PERMANENT The last server IPL used the


permanent copy of the server
firmware.

TEMPORARY The last server IPL used the


temporary copy of the server
firmware.

FW_IPL_REQUIRED IPL_REQD VARCHAR(3) Whether an IPL is required to activate PTFs for the
server firmware product.

NO PTFs are active.

YES PTFs are applied but are not active.

FW_PRODUCT_ID PRODUCT_ID VARCHAR(7) The IBM i product that matches the level of the
server firmware on the system. Managing the server
Nullable firmware level is performed by applying or removing
PTFs for this product.
Contains the null value if no product ID exists for the
active server firmware.

FW_PRODUCT_RELEASE RELEASE VARCHAR(6) The release corresponding to FW_PRODUCT_ID.

Nullable Contains the null value if no product ID exists for the


active server firmware.

Notes
• The view requires the system to have access to the internet with the ability to access the FLRT website.
The FLRT website is:

https://www14.software.ibm.com/support/customercare/flrt/liteTable?prodKey=fw&format=json

• If the FLRT website is relocated, this view can be updated by the user. Use the Insert Generated SQL
feature in ACS to extract the source for the SYSTOOLS.FLRT_FW_INFO table function. Update the link
and recreate the table function.
• If any of the CL commands or SQL functions used by the view encounter an error, an error will be
returned to indicate the failure. The job log can be examined to determine the root cause of the
problem.
• This view is provided in the SYSTOOLS schema as an example of how to retrieve live data using an
SQL view and table function. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source
can be extracted and used as a model for building similar interfaces, or to create a customized version
within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the
service and examine the implementation.

Example
Examine the firmware fix level information for the partition.

SELECT * FROM SYSTOOLS.FIRMWARE_CURRENCY;

876 IBM i: Performance and Query Optimization


GROUP_PTF_CURRENCY view
The GROUP_PTF_CURRENCY is a view containing a query which implements a live comparison of the PTF
Groups installed on the partition against the service levels listed on the IBM Preventive Service Planning
website. The information is generally updated once a week.
When queried, the view uses the XMLTABLE and HTTPGETBLOB table functions to consume a live XML
feed from IBM Preventive Service Planning (PSP). If the partition cannot connect to the PSP website, the
PTF_GROUP_CURRENCY column will contain PSP INFORMATION NOT AVAILABLE. When querying this
view, the job CCSID cannot be 65535 or the query will fail.
The results of the query show which PTF Groups installed on the partition match the latest level made
available by IBM and those which have a more recent version available.
Authorization: See Note below.
The following table describes the columns in the view. The system name is GRPPTFCUR. The schema is
SYSTOOLS.
Table 217. GROUP_PTF_CURRENCY view

Column name System column name Data type Description

PTF_GROUP_CURRENCY GRP_CRNCY VARCHAR(46) A description of the PTF group's status. Values


returned are:
Nullable
INSTALLED LEVEL Indicates that the PTF
IS CURRENT Group level installed
matches the most current
level available from IBM

CURRENT AT THE Indicates that the most


NEXT IPL current PTF Group level
available from IBM is ready
to be applied when the next
IPL occurs.

UPDATE Indicates that a more


AVAILABLE recent PTF Group level is
available from IBM

PSP INFORMATION Indicates that the query


NOT AVAILABLE is unable to connect to
the external IBM PSP PTF
Group level feed.

Returns the null value if not applicable to this PTF


group.

PTF_GROUP_ID GRP_ID CHAR(7) The name of the PTF group.

Nullable

PTF_GROUP_TITLE GRP_TITLE VARCHAR(1000) The descriptive name of the PTF group.

Nullable

PTF_GROUP_LEVEL_INSTALLED GRP_LVL INTEGER The most recent level of this PTF Group installed on
the partition.
Nullable

PTF_GROUP_LEVEL_AVAILABLE GRP_IBMLVL INTEGER The PTF Group level which is available from IBM
PSP.
Nullable

LAST_UPDATED_BY_IBM GRP_UPDATE DATE The date that IBM made the latest PTF Group level
available.
Nullable

PTF_GROUP_RELEASE GRP_RLS VARCHAR(6) The release level of the PTF Group. For example,
'R730' indicates IBM i 7.3 release level.
Nullable

PTF_GROUP_STATUS_ON_SYSTEM GRP_SYSSTS VARCHAR(20) This column will always contain the value
'INSTALLED'.
Nullable

PTF_GROUP_LAST_UPDATED_BY_IBM GRP_LSTUPD CHAR(10) The date that IBM made the latest PTF Group level
available. This is the character form of the date
Nullable formatted as MM/DD/YYYY.

Database performance and query optimization 877


Notes
• The PSP website is:

https://public.dhe.ibm.com/services/us/igsc/PSP/xmldoc.xml

To determine the IP address for your geography, ping www.ibm.com.


• If the PSP website is relocated, this view can be updated by the user. Use the Insert Generated SQL
feature in ACS to extract the source for the SYSTOOLS.GROUP_PTF_CURRENCY view. Update the link
and recreate the view.
• The PTF_GROUP_STATUS_ON_SYSTEM column is included in this view to demonstrate that it would be
possible to create your own version of this query or view which includes information about PTF Groups
that are loaded, but not installed.
• This view is provided in the SYSTOOLS schema as an example of how to retrieve live data using an
SQL view and table function. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source
can be extracted and used as a model for building similar interfaces, or to create a customized version
within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the
service and examine the implementation.

Example
Compare the PTF Group service level detail, ordering the results from furthest behind to current.

SELECT * FROM SYSTOOLS.GROUP_PTF_CURRENCY


ORDER BY PTF_GROUP_LEVEL_AVAILABLE - PTF_GROUP_LEVEL_INSTALLED DESC

Related reference
SYSTOOLS
SYSTOOLS is a set of Db2 for IBM i supplied examples and tools.

GROUP_PTF_DETAILS view
The GROUP_PTF_DETAILS is a view containing a query which implements a live comparison of the PTFs
within PTF Groups installed on the partition against the service levels listed on the IBM Preventive Service
Planning website.
When queried, the view uses the XMLTable() and HTTPGETBLOB() table functions to consume a live XML
feed from IBM Preventive Service Planning (PSP). If the partition cannot connect to the PSP website, the
query will fail with an SQL4302. When querying this view, the job CCSID cannot be 65535 or the query
will fail.
The results of the query show which PTFs from all PTF Groups installed on the partition match the latest
level made available by IBM and those which have a more recent version available.
Authorization: See Note below.
The following table describes the columns in the view. The system name is GRPPTFDTL. The schema is
SYSTOOLS.
Table 218. GROUP_PTF_DETAILS view

Column name System column Data type Description


name

PTF_GROUP_DESCRIPTION GRPDESC VARCHAR(100) Description of the PTF group.

PTF_GROUP_NAME GRPNAME CHAR(7) Name of the PTF group.

878 IBM i: Performance and Query Optimization


Table 218. GROUP_PTF_DETAILS view (continued)

Column name System column Data type Description


name

PTF_STATUS PTF_STATUS VARCHAR(11) Status of the PTF.

PTF APPLIED The PTF has been loaded and applied.

PTF LOADED The PTF has been loaded but not


applied.

PTF MISSING The PTF does not exists on this partition.

PTF_PRODUCT_ID LICPGM VARCHAR(7) The licensed program for this PTF.

PTF_IDENTIFIER PTFID VARCHAR(7) The identifier of the PTF.

APAR_NAME APAR_NAME VARCHAR(7) The APAR name associated with the PTF.

INCLUDED_IN_GROUP INCLUDED DATE The date that this PTF was first made available in a group
PTF.

PTF_CUM_PACKAGE PTF_CUMPKG VARCHAR(8) The identifier of the cumulative PTF package containing
this PTF.

PTF_PRODUCT_DESCRIPTION PRODDESC VARCHAR(132) Product description.

Nullable

PTF_RELEASE_LEVEL PTFRLS VARCHAR(6) The release level of the PTF.

Nullable

PTF_PRODUCT_LOAD PRODLOAD VARCHAR(4) The load ID of the product load for the PTF.

Nullable

PTF_LOADED_STATUS LOADSTAT VARCHAR(19) The current loaded status of the PTF.

Nullable NOT LOADED The PTF has never been loaded.

LOADED The PTF has been loaded.

APPLIED The PTF has been applied.

PERMANENTLY The PTF has been applied


APPLIED permanently.

PERMANENTLY The PTF has been permanently


REMOVED removed.

DAMAGED The PTF is damaged. An error


occurred while applying the PTF. It
needs to be reloaded and applied.

SUPERSEDED The PTF is superseded. A PTF will


have a status of superseded when
one of the following situations occurs:
• Another PTF with a more
recent correction for the problem
has been loaded on the
system. The PTF ID that has
been loaded can be found
in the PTF_SUPERSEDED_BY_PTF
column.
• The PTF save file for another PTF
with a more recent correction for
the problem has been logged into
*SERVICE on the system.

PTF_SAVE_FILE SAVF VARCHAR(3) Indicates whether a save file exists for the PTF.

Nullable NO The PTF has no save file.

YES The PTF has a save file.

PTF_COVER_LETTER COVER VARCHAR(3) Indicates whether a cover letter exists for the PTF.

Nullable NO The PTF has no cover letter.

YES The PTF has a cover letter.

Database performance and query optimization 879


Table 218. GROUP_PTF_DETAILS view (continued)

Column name System column Data type Description


name

PTF_ON_ORDER ONORD VARCHAR(3) Indicates whether the PTF has been ordered.

Nullable NO The PTF has not been ordered or has already been
received.

YES The PTF has been ordered.

PTF_IPL_ACTION IPLACT VARCHAR(19) The action to be taken on this PTF during the next
unattended IPL.
Nullable
NONE No action occurs at the next IPL.

TEMPORARILY The PTF is temporarily applied at


APPLIED the next IPL.

TEMPORARILY The PTF is temporarily removed


REMOVED at the next IPL.

PERMANENTLY The PTF is permanently applied


APPLIED at the next IPL.

PERMANENTLY The PTF is permanently removed


REMOVED at the next IPL.

PTF_ACTION_PENDING ACTPEND VARCHAR(3) Indicates whether a required action has yet to be


performed to make this PTF active.
Nullable
NO No required actions are pending for this PTF.

YES A required action needs to occur for this PTF to be


active. Check the Activation Instructions section
of the cover letter to determine what the action
is. If the PTF_ACTION_REQUIRED column is set
to IPL and the activation instructions have been
performed, then the PTF is active. However, this
column will not be updated until the next IPL.

PTF_ACTION_REQUIRED ACTREQ VARCHAR(12) Indicates whether an action is required to make this PTF
active when it is applied. See the cover letter to determine
Nullable what action needs to be taken.

NONE No activation instructions are needed for


this PTF.

EXIT This PTF was shipped with activation


PROGRAM instructions in the cover letter. This value
is returned for all PTFs that have an
exit program to update the status of the
PTF after the activation instructions have
been performed.

IPL This PTF was shipped with activation


instructions in the cover letter. No exit
program exists to verify the activation
instructions were performed.

PTF_IPL_REQUIRED IPLREQ VARCHAR(9) Indicates whether an IPL is required to apply this PTF.

Nullable DELAYED The PTF is delayed. The PTF must be


applied during an IPL.

IMMEDIATE The PTF is immediate. No IPL is needed to


apply the PTF.

UNKNOWN The type of the PTF is not known.

PTF_IS_RELEASED RELEASED VARCHAR(3) Indicates whether the PTF save file is available for
distribution to another system. This is set to YES only when
Nullable the System Manager for IBM i licensed program is on the
system and the product is supported. The PTF_SAVE_FILE
column must have a value of YES before using the value in
this column.

NO The PTF save file cannot be distributed.

YES The PTF save file is released and can be


distributed to another system.

880 IBM i: Performance and Query Optimization


Table 218. GROUP_PTF_DETAILS view (continued)

Column name System column Data type Description


name

PTF_MINIMUM_LEVEL MINLVL VARCHAR(2) The indicator of the lowest level of the product to which
this PTF can be applied. The level can be AA to 99.
Nullable
Contains the null value if the product does not have a level.

PTF_MAXIMUM_LEVEL MAXLVL VARCHAR(2) The indicator of the highest level of the product to which
this PTF can be applied. The level can be AA to 99.
Nullable
Contains the null value if the product does not have a level.

PTF_STATUS_TIMESTAMP STATTIME TIMESTAMP The date and time that the PTF status was last changed.

Nullable Contains the null value when the status date and time is
not available.

PTF_SUPERSEDED_BY_PTF SUPERSEDE VARCHAR(7) The identifier of the PTF that has replaced this PTF.

Nullable This field will be blank when the PTF is not superseded
or when the superseding PTF has not been loaded on the
system.

PTF_CREATION_TIMESTAMP CRTTIME TIMESTAMP The date and time that the PTF was created.

Nullable Contains the null value when the creation date and time
cannot be determined.

PTF_INCLUDED_IN_GROUP_DATE PTF_DATE VARCHAR(10) The date that this PTF was first made available in a group
PTF. Contains the character form of a date formatted as
MM/DD/YY.

Notes
The PSP websites used by this service are found based upon the PTF groups that are currently installed
on the partition. For each distinct PTF group, a unique PSP XML feed is accessed:

https://public.dhe.ibm.com/services/us/igsc/PSP/<PTF-Group-Name>.xml

For example, the JAVA PTF group details can be accessed using:

https://public.dhe.ibm.com/services/us/igsc/PSP/SF99572.xml

To determine the IP address for your geography, ping www.ibm.com.


This view is provided in the SYSTOOLS schema as an example of how to retrieve live data using an SQL
view and table function. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can be
extracted and used as a model for building similar interfaces, or to create a customized version within a
user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
• Review the details for the PTFs which have not yet been applied for the PTF groups installed on this
partition.

SELECT * FROM SYSTOOLS.GROUP_PTF_DETAILS


WHERE PTF_STATUS <> 'PTF APPLIED'
ORDER BY PTF_GROUP_NAME

Related reference
SYSTOOLS

Database performance and query optimization 881


SYSTOOLS is a set of Db2 for IBM i supplied examples and tools.

GROUP_PTF_INFO view
The GROUP_PTF_INFO view contains information about the group PTFs for the server.
The information returned is similar to the information available from Work with PTF Groups (WRKPTFGRP)
CL command.
Authorization: The caller must have *USE authority to the Work with PTF Groups (WRKPTFGRP)
command.
The following table describes the columns in the view. The system name is GRPPTFINFO. The schema is
QSYS2.
Table 219. GROUP_PTF_INFO view

Column name System column name Data type Description

COLLECTED_TIME COLLE00001 TIMESTAMP Date and time of when this row information was
generated.

PTF_GROUP_NAME PTF_G00001 VARCHAR(60) Name of the PTF group.

Nullable

PTF_GROUP_DESCRIPTION PTF_G00002 VARCHAR(100) Description of the PTF group.

Nullable

PTF_GROUP_LEVEL PTF_G00003 INTEGER Level of the PTF group.

Nullable

PTF_GROUP_TARGET_RELEASE PTF_G00004 VARCHAR(6) Release level for PTF group.

Nullable

882 IBM i: Performance and Query Optimization


Table 219. GROUP_PTF_INFO view (continued)

Column name System column name Data type Description

PTF_GROUP_STATUS PTF_G00005 VARCHAR(20) Status of the PTF group.

Nullable UNKNOWN The PTF group status cannot be


resolved because a related PTF
group is either not found on the
system or is in error.

NOT All PTFs in the PTF group and


APPLICABLE related PTF groups are for products
that are not installed or supported
on this system.

SUPPORTED There are no PTFs in the PTF group


ONLY or related PTF groups that are for
installed products on this system.
There is at least one PTF that is for
a product, release, option, and load
identifier that is supported on this
system.

NOT There is at least one PTF that is for


INSTALLED an installed product on this system,
and not all of the PTFs or their
superseding PTFs are temporarily or
permanently applied.

INSTALLED All PTFs for products that are


installed on this system are
temporarily or permanently applied.
If a PTF is superseded, a superseding
PTF is either temporarily or
permanently applied.

ERROR The PTF group information is in


error. Either delete the PTF group or
replace the PTF group information
that is currently on the system.

APPLY AT All PTFs for the installed products


NEXT IPL on the system are either set to be
applied at the next IPL or are already
temporarily or permanently applied.

RELATED The PTF group does not have


GROUP any PTFs for products installed or
supported on the system. However, it
is identified in another PTF group as
a related PTF group. Deleting a PTF
group in this status will cause the
other PTF group to have a status of
UNKNOWN.

ON ORDER There is at least one PTF in the group


that is on order and has not yet been
installed on the system. It will be
delivered on either physical or virtual
media.

Example
Determine the level of the latest CUM PTF group installed on the system.

SELECT MAX(PTF_GROUP_LEVEL) AS CUM_LEVEL


FROM QSYS2.GROUP_PTF_INFO
WHERE PTF_GROUP_NAME IN ('SF99610','SF99710')
AND PTF_GROUP_STATUS = 'INSTALLED'

PTF_COVER_LETTER table function


The PTF_COVER_LETTER table function returns the cover letter content for a PTF.
The information returned is similar to what is returned by the Display PTF Cover Letter (DSPPTFCVR)
command.

Database performance and query optimization 883


Authorization: See Note below.

PTF_COVER_LETTER ( ptf-id
PTF_ID =>

)
, ignore_errors
IGNORE_ERRORS =>

The schema is SYSTOOLS.

ptf-id The PTF identifier for the cover letter to be returned.


ignore-errors A character string that identifies what to do when an error is encountered.

NO An error is returned.

YES A warning is returned.


No row is returned when an error is encountered. This is the default.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 220. PTF_COVER_LETTER table function

Column Name Data Type Description

LINE_NUMBER INTEGER The position of this row in the PTF cover letter. The first
row has a value of 1.

PTF_COVER_LETTER_LINE VARCHAR(80) The data for this row in the PTF cover letter.

Note
This function is provided in the SYSTOOLS schema as an example of how to return PTF cover letter
information from a system file by using an SQL table function. Similar to other Db2 for i provided tools
within SYSTOOLS, the SQL source can be extracted and used as a model for building similar helper
functions, or to create a customized version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Return cover letters for any PTFs that have been loaded but not applied.

WITH PTFS (PTF_ID) AS (


SELECT PTFID FROM QSYS2.PTF_INFO
WHERE PTF_COVER_LETTER = 'YES' AND
PTF_LOADED_STATUS = 'LOADED')
SELECT PTF_ID, C.*
FROM PTFS, TABLE (SYSTOOLS.PTF_COVER_LETTER(PTF_ID)) C
ORDER BY 1, 2;

PTF_INFO view
The PTF_INFO view contains information about PTFs for the server.
The information returned is similar to QpzListPTF API.
Authorization: The caller must have *USE authority to the Display Program Temporary Fix (DSPPTF)
command.

884 IBM i: Performance and Query Optimization


The following table describes the columns in the view. The schema is QSYS2.
Table 221. PTF_INFO view

Column name System column Data type Description


name

PTF_PRODUCT_ID LICPGM VARCHAR(7) Product identifier.

Nullable

PTF_PRODUCT_OPTION PRODOPT VARCHAR(6) Product option.

Nullable

PTF_PRODUCT_OPTION_2 PRODOPT2 VARCHAR(6) Product option. The column contains the optional part
number or *BASE.
Nullable

PTF_PRODUCT_RELEASE_LEVEL PRODRLS VARCHAR(6) Product release level.

Nullable

PTF_PRODUCT_DESCRIPTION PRODDESC VARCHAR(132) Product description.

Nullable

PTF_IDENTIFIER PTFID VARCHAR(7) The identifier of the PTF.

Nullable

PTF_RELEASE_LEVEL PTFRLS VARCHAR(6) The release level of the PTF.

Nullable

PTF_PRODUCT_LOAD PRODLOAD VARCHAR(4) The load ID of the product load for the PTF.

Nullable

PTF_LOADED_STATUS LOADSTAT VARCHAR(19) The current loaded status of the PTF.

Nullable NOT LOADED The PTF has never been loaded.

LOADED The PTF has been loaded.

APPLIED The PTF has been temporarily


applied.

PERMANENTLY The PTF has been applied


APPLIED permanently.

PERMANENTLY The PTF has been permanently


REMOVED removed.

DAMAGED The PTF is damaged. An error


occurred while applying the PTF. It
needs to be reloaded and applied.

SUPERSEDED The PTF is superseded. A PTF


will have a status of superseded
when one of the following situations
occurs:
• Another PTF with a more
recent correction for the problem
has been loaded on the
system. The PTF ID that has
been loaded can be found
in the PTF_SUPERSEDED_BY_PTF
column.
• The PTF save file for another PTF
with a more recent correction for
the problem has been logged into
*SERVICE on the system.

PTF_SAVE_FILE SAVF VARCHAR(3) Indicates whether a save file exists for the PTF.

Nullable NO The PTF has no save file.

YES The PTF has a save file.

Database performance and query optimization 885


Table 221. PTF_INFO view (continued)

Column name System column Data type Description


name

PTF_COVER_LETTER COVER VARCHAR(3) Indicates whether a cover letter exists for the PTF.

Nullable NO The PTF has no cover letter.

YES The PTF has a cover letter.

PTF_ON_ORDER ONORD VARCHAR(3) Indicates whether the PTF has been ordered.

Nullable NO The PTF has not been ordered or has already been
received.

YES The PTF has been ordered.

PTF_IPL_ACTION IPLACT VARCHAR(19) The action to be taken on this PTF during the next
unattended IPL.
Nullable
NONE No action occurs at the next IPL.

TEMPORARILY The PTF is temporarily applied at


APPLIED the next IPL.

TEMPORARILY The PTF is temporarily removed


REMOVED at the next IPL.

PERMANENTLY The PTF is permanently applied


APPLIED at the next IPL.

PERMANENTLY The PTF is permanently removed


REMOVED at the next IPL.

PTF_ACTION_PENDING ACTPEND VARCHAR(3) Indicates whether a required action has yet to be


performed to make this PTF active.
Nullable
NO No required actions are pending for this PTF.

YES A required action needs to occur for this PTF to be


active. Check the Activation Instructions section
of the cover letter to determine what the action
is. If the PTF_ACTION_REQUIRED column is set
to IPL and the activation instructions have been
performed, then the PTF is active. However, this
column will not be updated until the next IPL.

PTF_ACTION_REQUIRED ACTREQ VARCHAR(12) Indicates whether an action is required to make this PTF
active when it is applied. See the cover letter to determine
Nullable what action needs to be taken.

NONE No activation instructions are needed for


this PTF.

EXIT This PTF was shipped with activation


PROGRAM instructions in the cover letter. This value
is returned for all PTFs that have an
exit program to update the status of the
PTF after the activation instructions have
been performed.

IPL This PTF was shipped with activation


instructions in the cover letter. No exit
program exists to verify the activation
instructions were performed.

PTF_IPL_REQUIRED IPLREQ VARCHAR(9) Indicates whether an IPL is required to apply this PTF.

Nullable DELAYED The PTF is delayed. The PTF must be


applied during an IPL.

IMMEDIATE The PTF is immediate. No IPL is needed to


apply the PTF.

UNKNOWN The type of the PTF is not known.

886 IBM i: Performance and Query Optimization


Table 221. PTF_INFO view (continued)

Column name System column Data type Description


name

PTF_IS_RELEASED RELEASED VARCHAR(3) Indicates whether the PTF save file is available for
distribution to another system. This is set to YES only
Nullable when the System Manager for IBM i licensed program
is on the system and the product is supported. The
PTF_SAVE_FILE column must have a value of YES before
using the value in this column.

NO The PTF save file cannot be distributed.

YES The PTF save file is released and can be


distributed to another system.

PTF_MINIMUM_LEVEL MINLVL VARCHAR(2) The indicator of the lowest level of the product to which
this PTF can be applied. The level can be AA to 99.
Nullable
Contains the null value if the product does not have a
level.

PTF_MAXIMUM_LEVEL MAXLVL VARCHAR(2) The indicator of the highest level of the product to which
this PTF can be applied. The level can be AA to 99.
Nullable
Contains the null value if the product does not have a
level.

PTF_STATUS_TIMESTAMP STATTIME TIMESTAMP The date and time that the PTF status was last changed.

Nullable Contains the null value when the status date and time is
not available.

PTF_SUPERSEDED_BY_PTF SUPERSEDE VARCHAR(7) The identifier of the PTF that has replaced this PTF.

Nullable This field will be blank when the PTF is not superseded
or when the superseding PTF has not been loaded on the
system.

PTF_LATEST_SUPERSEDING_PTF LATEST_PTF VARCHAR(7) The identifier of the most recent PTF that has superseded
this PTF.
Nullable
Contains the null value when PTF_LOADED_STATUS is not
PERMANENTLY APPLIED or SUPERSEDED.

PTF_CREATION_TIMESTAMP CRTTIME TIMESTAMP The date and time that the PTF was created.

Nullable Contains the null value when the creation date and time
cannot be determined.

PTF_TECHNOLOGY_REFRESH_PTF TRPTF VARCHAR(3) Indicates whether this is a technology refresh PTF.

Nullable NO This is not a technology refresh PTF.

YES This is a technology refresh PTF.

PTF_TEMPORARY_APPLY_TIMESTAMP TMPTIME TIMESTAMP The date and time that the PTF was temporarily applied.

Nullable Contains the null value if the PTF has not been temporarily
applied.

Examples
• Find which PTFs will be impacted by the next IPL.

SELECT PTF_IDENTIFIER, PTF_IPL_ACTION, A.*


FROM QSYS2.PTF_INFO A
WHERE PTF_IPL_ACTION <> 'NONE‘

• Find which PTFs are loaded but not applied.

SELECT PTF_IDENTIFIER, PTF_PRODUCT_DESCRIPTION, A.*


FROM QSYS2.PTF_INFO A
WHERE PTF_LOADED_STATUS = 'LOADED'
ORDER BY PTF_PRODUCT_ID

Security Services
These views, procedures, and functions provide security information.

Database performance and query optimization 887


AUTHORITY_COLLECTION views
The AUTHORITY_COLLECTION views returns information about the authority check for an object.
See Authority collection views for the description of the view.

AUTHORIZATION_LIST_INFO view
The AUTHORIZATION_LIST_INFO view returns a list of all objects secured by an authorization list.
The information returned is similar to the information available through the Display Authorization List
Objects (DSPAUTLOBJ) CL command and the List Objects Secured by Authorization List (QSYLATLO) API.
Authorization: The caller must have:
• *READ authority to the authorization list, or
• Authorized to the QIBM_DB_SECADM function usage identifier.
The following table describes the columns in the view. The system name is AUTHL_INFO. The schema is
QSYS2.
Table 222. AUTHORIZATION_LIST_INFO view

Column name System column name Data type Description

AUTHORIZATION_LIST AUTH_LIST VARCHAR(10) The authorization list for this object.

SYSTEM_OBJECT_SCHEMA SYS_DNAME VARCHAR(10) The library that contains the object.

Nullable Returns the null value if the object is not in the QSYS
or QDLS file system.

SYSTEM_OBJECT_NAME SYS_ONAME VARCHAR(10) The object that is secured by the authorization list.

Nullable Returns the null value if the object is not in the QSYS
or QDLS file system.

SYSTEM_OBJECT_TYPE SYS_OTYPE VARCHAR(8) The system object type of the secured object.

OBJECT_ATTRIBUTE OBJATTR VARCHAR(5) The attribute for the secured object's type.

Nullable Returns the null value if the object has no attribute


or if it is not in the QSYS or QDLS file system.

OBJECT_SCHEMA OSCHEMA VARCHAR(128) The SQL schema name for this object.

Nullable Returns the null value if the object is not in the QSYS
or QDLS file system.

OBJECT_NAME ONAME VARCHAR(128) The SQL name of the object.

Nullable For an external procedure or an external function,


the name will be returned when a single procedure
or function exists for that *PGM or *SRVPGM object.
Contains the null value if an SQL name could not be
returned.

888 IBM i: Performance and Query Optimization


Table 222. AUTHORIZATION_LIST_INFO view (continued)

Column name System column name Data type Description

OBJECT_TYPE OTYPE VARCHAR(9) The SQL object type. The following values can be
returned.
Nullable
ALIAS The object is an SQL alias.

FUNCTION The object is an SQL function.

INDEX The object is an SQL index.

PACKAGE The object is an SQL package.

PROCEDURE The object is an SQL procedure.

ROUTINE The object is used in SQL by one


or more external functions and/or
external procedures.

SEQUENCE The object is an SQL sequence.

TABLE The object is an SQL table.

TRIGGER The object is an SQL trigger.

TYPE The object is an SQL type.

VARIABLE The object is an SQL global


variable.

VIEW The object is an SQL view.

XSR The object is an XML schema


repository object.

Returns the null value if the object is not an SQL


object.

OBJECT_OWNER OWNER VARCHAR(10) The owner of the object.

PRIMARY_GROUP GROUP VARCHAR(10) The user who is the primary group for the object.

Nullable Returns the null value if there is no primary group for


the object.

TEXT_DESCRIPTION TEXT VARCHAR(50) The descriptive text for the secured object.

Nullable Returns the null value if the object is not in the QSYS
or QDLS file system.

ASPGRP ASPGRP VARCHAR(10) The name of the ASP device containing the object. A
value of *SYSBAS indicates the system ASP and all
basic user ASPs.

AUTHORITY_HOLDER AUT_HOLDER VARCHAR(3) Indicates whether the object is an authority holder.

NO The object is not an authority holder.

YES The object is an authority holder.

PATH_NAME PATH_NAME DBCLOB(16M) The path name for the object that is secured by the
CCSID 1200 authorization list.
Nullable Returns the null value if the object is in the QSYS or
QDLS file system.

DLO_NAME DLO_NAME VARCHAR(12) The document library object (DLO) name for the
object.
Nullable
Returns the null value if OBJECT_TYPE is not *DOC
(document) or *FLR (folder).

FOLDER_PATH FOLDER VARCHAR(63) The name of the folder that contains the DLO object.

Nullable Returns the null value if the object is not in a folder.

Example
Return information about all the object secured by authorization list APP1.

SELECT * FROM QSYS2.AUTHORIZATION_LIST_INFO WHERE AUTHORIZATION_LIST = 'APP1';

Database performance and query optimization 889


AUTHORIZATION_LIST_USER_INFO view
The AUTHORIZATION_LIST_USER_INFO view returns a list of all authorization lists and their authorities.
The information returned is similar to the information available through the Display Authorization List
(DSPAUTL) CL command.
Authorization: None required.
The following table describes the columns in the view. The system name is AUTL_USERS. The schema is
QSYS2.
Table 223. AUTHORIZATION_LIST_USER_INFO view

Column name System column name Data type Description

AUTHORIZATION_LIST AUTL VARCHAR(10) The name of the authorization list.

AUTHORIZATION_NAME USER_NAME VARCHAR(10) User profile name. Can contain the following special
value.

*PUBLIC This row contains the public authority


for the object.

OBJECT_AUTHORITY OBJ_AUTH VARCHAR(12) The authority that the user has to the object.
Contains one of the following values:

*ALL Allows all operations on the


object except those that are
limited to the owner or controlled
by authorization list management
authority.

*CHANGE Allows all operations on the object


except those that are limited
to the owner or controlled by
object existence authority, object
alter authority, object reference
authority, and object management
authority.

*EXCLUDE All operations on the object are


prohibited.

*USE Allows access to the object


attributes and use of the object.
The user cannot change the object.

USER The specific object authorities and


DEFINED data authorities do not match any
of the predefined object authority
levels.

AUTHORIZATION_LIST_MANAGEMENT AUTL_MGMT VARCHAR(3) The authorization list management authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OWNER OWNER VARCHAR(10) The owner of the authorization list.

OBJECT_OPERATIONAL OBJOPER VARCHAR(3) The object operational authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_MANAGEMENT OBJMGT VARCHAR(3) The object management authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

890 IBM i: Performance and Query Optimization


Table 223. AUTHORIZATION_LIST_USER_INFO view (continued)

Column name System column name Data type Description

OBJECT_EXISTENCE OBJEXIST VARCHAR(3) The object existence authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_ALTER OBJALTER VARCHAR(3) The object alter authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_REFERENCE OBJREF VARCHAR(3) The object reference authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_READ DATA_READ VARCHAR(3) The data read authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_ADD DATA_ADD VARCHAR(3) The data add authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_UPDATE DATA_UPD VARCHAR(3) The data update authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_DELETE DATA_DEL VARCHAR(3) The data delete authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_EXECUTE DATA_EXEC VARCHAR(3) The data execute authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

TEXT_DESCRIPTION TEXT VARCHAR(50) The descriptive text for the authorization list.

Nullable Contains null if the authorization list has no text


description.

Example
List the public security settings for all authorization lists.

SELECT *
FROM QSYS2.AUTHORIZATION_LIST_USER_INFO
WHERE AUTHORIZATION_NAME = '*PUBLIC';

Database performance and query optimization 891


CERTIFICATE_INFO table function
The CERTIFICATE_INFO table function returns a result table that contains information about server or
Certificate Authority (CA) certificates.
This information is similar to what is returned by the Retrieve Certificate Information (QYCURTVCI,
QycuRetrieveCertificateInfo) API.
Authorization: The caller must provide the password for the certificate store. In addition, the caller must
have *ALLOBJ and *SECADM special authorities.

CERTIFICATE_INFO (

certificate-store-password
CERTIFICATE_STORE_PASSWORD =>

)
, certificate-store
CERTIFICATE_STORE =>

The schema is QSYS2.

certificate- An expression that contains the password for the specified certificate store. It is
store- recommended that the password be passed as a variable, not as a string visible as clear
password text.
The following value can be used instead of specifying the password.

*NOPWD The certificate store password will be retrieved from the stashed password
file.

certificate- A character or graphic string expression that indicates the certificate store from which a
store list of certificates is to be retrieved. The value can either be a fully qualified Integrated File
System (IFS) directory path and file name of the certificate store, starting with a leading
forward slash (/), or one of the following special values. If the file name does not identify
a certificate store, no rows are returned. If certificate-store is not specified, *SYSTEM is the
default.

*OBJECTSIGNING The *OBJECTSIGNING certificate store.


*SIGNATUREVERIFICATION The *SIGNATUREVERIFICATION certificate store.
*SYSTEM The *SYSTEM certificate store.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 224. CERTIFICATE_INFO table function

Column Name Data Type Description

CERTIFICATE_LABEL VARCHAR(256) The label for the certificate.

SERIAL_NUMBER VARCHAR(64) Serial number.

VALIDITY_START TIMESTAMP(0) The beginning date of the validity period.

VALIDITY_END TIMESTAMP(0) The ending date of the validity period.

TRUSTED VARCHAR(3) Indicates if the certificate is trusted.

NO The certificate is not trusted.

YES The certificate is trusted.

KEY_SIZE INTEGER The size of the key, in bytes.

892 IBM i: Performance and Query Optimization


Table 224. CERTIFICATE_INFO table function (continued)

Column Name Data Type Description

PRIVATE_KEY VARCHAR(3) Indicates if the certificate has a private key.

NO The certificate does not have a private key.

YES The certificate has a private key.

PRIVATE_KEY_LABEL VARCHAR(64) The private key label.


Contains the null value if PRIVATE_KEY is NO or if
PRIVATE_KEY_STORAGE_LOCATION is SOFTWARE.

PRIVATE_KEY_STORAGE_LOCATION VARCHAR(19) Where the key is stored.

HARDWARE The key is stored in hardware.

HARDWARE ENCRYPTION The key is stored in hardware encryption.

SOFTWARE The key is stored is software.

Contains the null value if PRIVATE_KEY is NO.

DIGITAL_SIGNATURE VARCHAR(3) The certificate has the digital signature extension.

NO The certificate does not have the digital signature extension.

YES The certificate has the digital signature extension.

NONREPUDIATION VARCHAR(3) Indicates if the certificate has the nonrepudiation extension.

NO The certificate does not have the nonrepudiation extension.

YES The certificate has the nonrepudiation extension.

KEY_ENCIPHERMENT VARCHAR(3) Indicates if the certificate has the key encipherment extension.

NO The certificate does not have the key encipherment extension.

YES The certificate has the key encipherment extension.

DATA_ENCIPHERMENT VARCHAR(3) Indicates if the certificate has the data encipherment extension.

NO The certificate does not have the data encipherment extension.

YES The certificate has the data encipherment extension.

KEY_AGREEMENT VARCHAR(3) Indicates if the certificate has the key agreement extension

NO The certificate does not have the key agreement extension.

YES The certificate has the key agreement extension.

KEY_CERTIFICATE_SIGNATURE VARCHAR(3) Indicates if the certificate has the key certificate signature extension.

NO The certificate does not have the key certificate signature extension.

YES The certificate has the key certificate signature extension.

CRL_SIGNATURE VARCHAR(3) Indicates if the certificate has the Certificate Revocation List (CRL) signature
extension.

NO The certificate does not have the CRL signature extension.

YES The certificate has the CRL signature extension.

CRL_LOCATION VARCHAR(50) The CRL location.


Contains the null value if no value is available.

ENCIPHER_ONLY VARCHAR(3) Indicates if the certificate has the encipher only extension.

NO The certificate does not have the encipher only extension.

YES The certificate has the encipher only extension.

DECIPHER_ONLY VARCHAR(3) Indicates if the certificate has the decipher only extension.

NO The certificate does not have the decipher only extension.

YES The certificate has the decipher only extension.

Database performance and query optimization 893


Table 224. CERTIFICATE_INFO table function (continued)

Column Name Data Type Description

LDAP_SERVER_NAME VARCHAR(900) The LDAP server name.


Contains the null value if no value is available.

IP_ADDRESS_COUNT INTEGER The number of addresses in the IP_ADDRESSES column. Currently, only one
IP address is returned.
Contains the null value if no IP addresses are available.

IP_ADDRESSES VARCHAR(45) The IP address.


Contains the null value if no value is available.

DOMAIN_NAME_COUNT INTEGER The number of domain names in the DOMAIN_NAMES column. Currently,
only one domain name is returned.
Contains the null value if no domain names are available.

DOMAIN_NAMES VARCHAR(256) The domain name.


Contains the null value if no value is available.

EMAIL_ADDRESS VARCHAR(256) The email address.


Contains the null value if no value is available.

CRYPTOGRAPHIC_DEVICE_COUNT INTEGER The number of cryptographic devices.

CRYPTOGRAPHIC_DEVICES VARCHAR(109) A list of cryptographic device descriptions. Each entry is ten characters long.
A single blank separates entries.
Contains the null value if CRYTOGRAPHIC_DEVICE_COUNT is 0.

SUBJECT_COMMON_NAME VARCHAR(256) The subject's common name. The SUBJECT set of columns define
information about the end-entity that is being described for the certificate.
Contains the null value if no value is available.

SUBJECT_ORGANIZATIONAL_UNIT VARCHAR(256) The subject's organizational unit.


Contains the null value if no value is available.

SUBJECT_ORGANIZATION VARCHAR(256) The subject's organization.


Contains the null value if no value is available.

SUBJECT_LOCALITY VARCHAR(128) The subject's locality.


Contains the null value if no value is available.

SUBJECT_STATE_PROVINCE VARCHAR(128) The subject's state or province.


Contains the null value if no value is available.

SUBJECT_POSTAL_CODE VARCHAR(16) The subject's postal code.


Contains the null value if no value is available.

SUBJECT_COUNTRY_REGION VARCHAR(3) The subject's country or region.


Contains the null value if no value is available.

ISSUER_COMMON_NAME VARCHAR(256) The issuer's common name. The ISSUER set of columns define information
about the Certificate Authority that signed the end-entity certificate.
Contains the null value if no value is available.

ISSUER_ORGANIZATIONAL_UNIT VARCHAR(256) The issuer's organizational unit.


Contains the null value if no value is available.

ISSUER_ORGANIZATION VARCHAR(256) The issuer's organization.


Contains the null value if no value is available.

ISSUER_LOCALITY VARCHAR(128) The issuer's locality.


Contains the null value if no value is available.

ISSUER_STATE_PROVINCE VARCHAR(128) The issuer's state or province.


Contains the null value if no value is available.

ISSUER_POSTAL_CODE VARCHAR(16) The issuer's postal code.


Contains the null value if no value is available.

894 IBM i: Performance and Query Optimization


Table 224. CERTIFICATE_INFO table function (continued)

Column Name Data Type Description

ISSUER_COUNTRY_REGION VARCHAR(3) The issuer's country or region.


Contains the null value if no value is available.

Example
Retrieve all the certificates for the *SYSTEM certificate store that will be expired within the next month.
Use a password that has been set in a global variable.

• CREATE VARIABLE MYLIB.SYSTEM_CERT_PW VARCHAR(30);

SET MYLIB.SYSTEM_CERT_PW = 'cert_pwd';

SELECT * FROM TABLE(QSYS2.CERTIFICATE_INFO(CERTIFICATE_STORE_PASSWORD=> MYLIB.SYSTEM_CERT_PW))


WHERE VALIDITY_END < CURRENT DATE + 1 MONTH;

CHANGE_USER_PROFILE table function


The CHANGE_USER_PROFILE table function changes a subset of user profile attributes.
For a detailed description of the parameters and their values, refer to CHGUSRPRF CL command.
Authorization: See Note below.

Database performance and query optimization 895


CHANGE_USER_PROFILE ( user-name
P_USER_NAME =>

, password
P_PASSWORD =>

, password-expired
P_PASSWORD_EXPIRED =>

, status
P_STATUS =>

, initial-program
P_INITIAL_PROGRAM =>

, limit-capabilities
P_LIMIT_CAPABILITIES =>

, text
P_TEXT =>

, password-expiration-interval
P_PASSWORD_EXPIRATION_INTERVAL =>

, job-description
P_JOB_DESCRIPTION =>

, group-profile
P_GROUP_PROFILE =>

, user-expiration-date
P_USER_EXPIRATION_DATE =>

, user-expiration-interval
P_USER_EXPIRATION_INTERVAL =>

, special-authority-action
P_SPECIAL_AUTHORITY_ACTION =>

, special-authority
P_SPECIAL_AUTHORITY =>

)
, preview
PREVIEW =>

The schema is SYSTOOLS.

user-name A character string containing the name of the user profile whose values are to be
changed.

896 IBM i: Performance and Query Optimization


password A character string containing a new password value for the user profile. This is the
PASSWORD parameter. The default is *SAME.
password- A character string that specifies whether the password for this user is set to expired.
expired This is the PWDEXP parameter. The default is *SAME.
status A character string that specifies the status of the user profile. This is the STATUS
parameter. The default is *SAME.
initial-program A character string that specifies the initial program to call. This is the INLPGM
parameter. The default is *SAME.
limit-capabilities A character string that specifies the capabilities for a user. This is the LMTCPB
parameter. The default is *SAME.
text A character string that specifies the descriptive text for the user profile. This is the
TEXT parameter. The default is *SAME.
password- A character string that specifies the password expiration interval, in days. This is the
expiration- PWDEXPITV parameter. The default is *SAME.
interval
job-description A character string that specifies the job description associated with this user profile
This is the JOBD parameter. The default is *SAME.
group-profile A character string that specifies the group profile associated with this user profile.
This is the GRPPRF parameter. The default is *SAME.
user-expiration- A character string that specifies the date when the user profile expires and is
date automatically disabled. This is the USREXPDATE parameter. The default is *SAME.
user-expiration- An integer value that specifies the expiration interval, in days, before the user profile
interval is automatically disabled. This is the USREXPITV parameter. The default is NULL,
meaning the value will not be changed.
special- A character string that specifies the action that applies to the special-authority
authority-action parameter. The default is *SAME.

*ADD The special authority should be added to the user profile.


*REMOVE The special authority should be removed from the user profile.

special-authority A character string that specifies a single special authority value to be added to or
removed from the user profile when the special-authority-action parameter has a
value or *ADD or *REMOVE. This is the SPCAUT parameter. The default is NULL,
meaning the value is not changed.
preview A character string that indicates whether the table function should execute the
CHGUSRPRF command that has been constructed based upon the input parameters
or whether only a preview of the potential action should be shown.

NO The table function should change the user profiles


YES The table function should return a preview of the changes. This is the default.

The result of the function is a table containing a single row with the details about the user profile change.
The columns of the result table are described in the following table. The result columns are nullable.
Table 225. CHANGE_USER_PROFILE table function

Column Name Data Type Description

USER_NAME VARCHAR(10) The user profile being changed or previewed.

Database performance and query optimization 897


Table 225. CHANGE_USER_PROFILE table function (continued)

Column Name Data Type Description

CHANGE_ATTEMPTED VARCHAR(3) Indicates whether the change was attempted.

NO The change was not attempted

YES The change was attempted

CHANGE_SUCCESSFUL VARCHAR(3) Indicates whether the change was successful.

NO The change was not successful

YES The change was successful

Contains the null value if CHANGE_ATTEMPTED is NO.

CHGUSRPRF_COMMAND VARCHAR(1000) The CHGUSRPRF command string.

FAILURE_MESSAGE_ID CHAR(7) The message ID.


Contains the null value if CHANGE_ATTEMPTED is NO or
CHANGE_SUCCESSFUL is YES.

FAILURE_MESSAGE_TEXT VARGRAPHIC(1024) The text of the message.

CCSID 1200 Contains the null value if CHANGE_ATTEMPTED is NO or


CHANGE_SUCCESSFUL is YES.

Note
This function is provided in the SYSTOOLS schema as a helper function to manage user profiles. Similar to
other Db2 for i provided tools within SYSTOOLS, the SQL source can be extracted and used as a model for
building similar helper functions, or to create a customized version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Disable all enabled user profiles that have no password set.
Preview the list of profiles that will be affected.

SELECT * FROM QSYS2.USER_INFO,


TABLE(SYSTOOLS.CHANGE_USER_PROFILE(
P_USER_NAME => AUTHORIZATION_NAME,
P_STATUS => '*DISABLED',
PREVIEW => 'YES'))
WHERE STATUS = '*ENABLED' AND
NO_PASSWORD_INDICATOR = 'YES';

Build and execute the CHGUSRPRF commands..

SELECT * FROM QSYS2.USER_INFO,


TABLE(SYSTOOLS.CHANGE_USER_PROFILE(
P_USER_NAME => AUTHORIZATION_NAME,
P_STATUS => '*DISABLED',
PREVIEW => 'NO'))
WHERE STATUS = '*ENABLED' AND
NO_PASSWORD_INDICATOR = 'YES';

DRDA_AUTHENTICATION_ENTRY_INFO view
The DRDA_AUTHENTICATION_ENTRY_INFO view returns user server authentication entry information.
A server authentication entry defines a userid and password to send on a connect request over
TCP/IP. A server authentication list is associated with every user profile on the system. The Add Server
Authentication Entry (ADDSVRAUTE) command is used to add entries.

898 IBM i: Performance and Query Optimization


When a DRDA connection over TCP/IP is attempted without specifying a userid and password, and
password authentication is required, the Db2 for i client checks the server authentication list for the
user profile under which the client job is running. If it finds a match between the RDB name on the
CONNECT statement and the server name in an authentication entry, or the server name is the special
value QDDMDRDASERVER, the associated userid (and password if one exists) is used for the connection.
A server authentication entry can also be used to specify a userid and password to be used for a DDM
connection over TCP/IP. When a DDM connection is attempted over TCP/IP, and password authentication
is required, the Db2 for i client checks the server authentication list for the user profile under which
the client job is running. If it finds a match between the RDB name specified in the DDM file and the
server name in an authentication entry, or the server name is the special value QDDMDRDASERVER, the
associated userid (and password if one exists) is used for the connection. If no RDB name is specified in
the DDM file and the server name is either of the special values QDDMDRDASERVER or QDDMSERVER, the
associated userid (and password if one exists) is used for the connection.
Authorization: The caller must have *OBJOPR and *READ authority to the *USRPRF object.
The following table describes the columns in the view. The system name is DRDA_AUTHE. The schema is
QSYS2.
Table 226. DRDA_AUTHENTICATION_ENTRY_INFO view

System Column
Column Name Name Data Type Description

AUTHORIZATION_NAME USER_NAME VARCHAR(10) The user profile on the client system.

SERVER_NAME SRVR_NAME VARGRAPHIC(200) The target system for the authentication entry.
CCSID 1200
This is the name of the RDB or QDDMDRDASERVER that is used
for connections made on behalf of RDB DDM files or DRDA
connections. For a non-RDB DDM file that does not use the RDB
directory, the value will be QDDMDRDASERVER or QDDMSERVER.
See Client security in a TCP/IP network for more information.

SERVER_AUTHORIZATION_NAME SRVR_USER VARGRAPHIC(1000) The user profile on the target system.


CCSID 1200

PASSWORD_STORED PW_STORED VARCHAR(3) Indicates whether a password is stored for the authentication
entry.

YES A password is stored for the authentication entry.

NO A password is not stored for the authentication entry.

Example
For an auditor, generate a list of user profiles that have authentication entries on the system:

SELECT DISTINCT(AUTHORIZATION_NAME)
FROM QSYS2.DRDA_AUTHENTICATION_ENTRY_INFO

FUNCTION_INFO view
The FUNCTION_INFO view contains details about function usage identifiers.
The values returned for the columns in the view are closely related to the values returned by the Display
Function Usage (DSPFCNUSG) CL command.
Authorization: None required.
The following table describes the columns in the view. The system name is FCN_INFO. The schema is
QSYS2.
Table 227. FUNCTION_INFO view

Column Name System Column Name Data Type Description

FUNCTION_ID FCNID VARCHAR(30) The function ID.

Nullable

Database performance and query optimization 899


Table 227. FUNCTION_INFO view (continued)

Column Name System Column Name Data Type Description

FUNCTION_CATEGORY FCNCAT VARCHAR(10) Indicates whether the function is a client or host function.

Nullable
1 - CLIENT The function is a locally managed client function within IBM i
Navigator.

2 - CLIENT The function is a locally managed client function, not within


IBM i Navigator.

3 - HOST The function is a host function.

4 - CLIENT The function is a centrally managed client function within IBM


i Navigator.

5 - CLIENT The function is a centrally managed client function, not within


IBM i Navigator.

FUNCTION_TYPE FCNTYP VARCHAR(13) The type of function.

Nullable
PRODUCT The function is a function product.

GROUP The function is a function group.

ADMINISTRABLE The function is an administrable function.

FUNCTION_NAME_MESSAGE_TEXT FCNMSGTXT VARGRAPHIC(330) The first-level text for the function-name message ID.
CCSID(1200)

Nullable

FUNCTION_NAME FCNNAM VARGRAPHIC(330) The text for the function name.


CCSID(1200)

Nullable

FUNCTION_DESCRIPTION_MESSAGE_ FCNDESCTXT VARGRAPHIC(330) The first-level text for the function-description message ID.
TEXT CCSID(1200)

Nullable

FUNCTION_DESCRIPTION FCNDESC VARGRAPHIC(330) The text for the function description.


CCSID(1200)

Nullable

FUNCTION_PRODUCT_ID FCNPRDID VARCHAR(30) The ID of the product that the function is registered for.

Nullable

FUNCTION_GROUP_ID FCNGRPID VARCHAR(30) The ID of the function group that the function is grouped with. If the function
is not grouped with a function group, this field is set to *NONE.
Nullable

DEFAULT_USAGE DFTUG VARCHAR(7) The default usage for the function.

Nullable
DENIED The default usage does not allow usage of the function.

ALLOWED The default usage allows usage of the function.

ALLOBJ_INDICATOR ALLOBJ VARCHAR(8) Indicates whether a user with *ALLOBJ special authority can use the function.

Nullable
NOT USED The user, its groups, or default must allow usage of the
function.

USED A user with *ALLOBJ special authority is always allowed to use


the function.

USAGE_INFORMATION_INDICATOR USGINFO VARCHAR(3) Indicates whether there is usage information defined for the function.

Nullable
NO There is no usage information defined for the function.

YES There is usage information defined for the function.

Example
Determine what function usage IDs exist and their default configuration.

SELECT * FROM QSYS2.FUNCTION_INFO ORDER BY FUNCTION_ID

900 IBM i: Performance and Query Optimization


FUNCTION_USAGE view
The FUNCTION_USAGE view contains function usage configuration details.
The values returned for the columns in the view are closely related to the values returned by the Display
Function Usage (DSPFCNUSG) CL command.
Authorization: The caller must have *SECADM special authority.
The following table describes the columns in the view. The system name is FCN_USAGE. The schema is
QSYS2.
Table 228. FUNCTION_USAGE view

Column Name System Column Name Data Type Description

FUNCTION_ID FCNID VARCHAR(30) The ID of the function.

USER_NAME USER_NAME VARCHAR(10) The name of the user profile that has a usage setting for this
function

USAGE USAGE VARCHAR(7) Usage setting.

ALLOWED The user profile is allowed to use the function.

DENIED The user profile is not allowed to use the function.

USER_TYPE USER_TYPE VARCHAR(5) Type of user profile.

USER The user profile is a user.

GROUP The user profile is a group.

Example
Determine what function usage has been granted or revoked.

SELECT * FROM QSYS2.FUNCTION_USAGE ORDER BY FUNCTION_ID, USER_NAME

GROUP_PROFILE_ENTRIES view
The GROUP_PROFILE_ENTRIES view contains one row for each user profile that is part of a group profile.
Both group profile (GRPPRF) and supplemental group profile (SUPGRPPRF) information is considered for
each user profile.
Authorization: The caller must have *READ authority to the user profile.
The following table describes the columns in the view. The system name is GROUPLIST. The schema is
QSYS2.
Table 229. GROUP_PROFILE_ENTRIES view

Column Name System Column Name Data Type Description

GROUP_PROFILE_NAME GROUPNAME VARCHAR(128) Group profile name

USER_PROFILE_NAME USERNAME VARCHAR(128) User profile name

USER_TEXT USER_TEXT VARCHAR(50) User profile text description.

Nullable

OBJECT_OWNERSHIP view
The OBJECT_OWNERSHIP view returns ownership information for all objects.
The values returned for the columns in the view are closely related to the values returned by the
WRKOBJOWN CL command and the List Objects User Is Authorized to, Owns, or Is Primary Group of
(QSYLOBJA) API.
Authorization: The caller must have *READ authority to the user profile that owns the object.

Database performance and query optimization 901


The following table describes the columns in the view. The system name is OBJ_OWN. The schema is
QSYS2.
Table 230. OBJECT_OWNERSHIP view

Column Name System Column Name Data Type Description

AUTHORIZATION_NAME USER_NAME VARCHAR(10) User profile that owns the object.

OBJECT_TYPE OBJ_TYPE VARCHAR(7) The type of object.

OBJECT_LIBRARY LIBNAME VARCHAR(10) The name of the library containing the object.

Nullable Contains the null value if OBJECT_NAME is null.

OBJECT_NAME NAME VARCHAR(10) The name of the object.

Nullable Contains the null value if OBJECT_TYPE is *BLKSF,


*CHRSF, *DIR, *FIFO, *STMF, or *SYMLNK.

PATH_NAME PATH_NAME DBCLOB(16M) The path name of the object.

CCSID 1200 Contains the null value if OBJECT_TYPE is


Nullable not *BLKSF, *CHRSF, *DIR, *FIFO, *STMF, or
*SYMLNK.

OBJECT_ATTRIBUTE ATTRIBUTE VARCHAR(10) The object's attribute.

Nullable Contains the null value if there is no attribute for


the object.

TEXT_DESCRIPTION TEXT VARCHAR(50) The descriptive text for this object.

Nullable Contains the null value if the object has no text


description.

IASP_NAME IASP_NAME VARCHAR(10) The auxiliary storage pool (ASP) device name
where the object is stored. If the object is in
the system ASP or one of the basic user ASPs,
contains *SYSBAS.

AUTHORITY_HOLDER AUT_HOLDER VARCHAR(3) Whether the object is an authority holder.

NO The object is not an authority holder.

YES The object is an authority holder.

AUTHORIZATION_LIST_MANAGEMENT AUTL_MGMT VARCHAR(3) Whether AUTHORIZATION_NAME has


authorization list management authority to the
Nullable object.

NO The user does not have authorization list


management authority.

YES The user has authorization list


management authority.

Contains the null value if OBJECT_TYPE is not


*AUTL.

902 IBM i: Performance and Query Optimization


Table 230. OBJECT_OWNERSHIP view (continued)

Column Name System Column Name Data Type Description

OBJECT_AUTHORITY OBJ_AUTH VARCHAR(12) The authority that AUTHORIZATION_NAME has to


the object. Contains one of the following special
values:

*ALL Allows all operations on the


object except those that are
limited to the owner or
controlled by authorization list
management authority.

*CHANGE Allows all operations on the


object except those that are
limited to the owner or
controlled by object existence
authority, object alter authority,
object reference authority, and
object management authority.

*EXCLUDE All operations on the object are


prohibited.

*USE Allows access to the object


attributes and use of the object.
The user cannot change the
object.

USER The specific object authorities


DEFINED and data authorities do not
match any of the predefined
object authority levels.

OBJECT_OPERATIONAL OBJOPER VARCHAR(3) Indicates the object operational authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_MANAGEMENT OBJMGT VARCHAR(3) The object management authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_EXISTENCE OBJEXIST VARCHAR(3) The object existence authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_ALTER OBJALTER VARCHAR(3) The object alter authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_REFERENCE OBJREF VARCHAR(3) The object reference authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_READ DATA_READ VARCHAR(3) The data read authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

Database performance and query optimization 903


Table 230. OBJECT_OWNERSHIP view (continued)

Column Name System Column Name Data Type Description

DATA_ADD DATA_ADD VARCHAR(3) The data add authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_UPDATE DATA_UPD VARCHAR(3) The data update authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_DELETE DATA_DEL VARCHAR(3) The data delete authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_EXECUTE DATA_EXEC VARCHAR(3) The data execute authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

Examples
• Return a list of all objects owned by user FRANKDBA.

SELECT * FROM QSYS2.OBJECT_OWNERSHIP


WHERE AUTHORIZATION_NAME = 'FRANKDBA';

• Return a list of only objects in the IFS that are owned by user FRANKDBA.

SELECT * FROM QSYS2.OBJECT_OWNERSHIP


WHERE AUTHORIZATION_NAME = 'FRANKDBA'
AND PATH_NAME IS NOT NULL;

OBJECT_PRIVILEGES table function


The OBJECT_PRIVILEGES table function returns a row for every user authorized to the specified object,
along with their associated object and data authorities.
The information returned is similar to the information available through the Display Object Authority
(DSPOBJAUT) CL command.
Authorization: All authorized users are returned for an object when at least one of the following is true:
• The caller has *OBJMGT authority.
• The caller is the owner of the object.
• The object is an authorization list.
• The caller is authorized to the QIBM_DB_SECADM function usage identifier.
Otherwise, only authorizations for the caller are returned.

904 IBM i: Performance and Query Optimization


OBJECT_PRIVILEGES ( system-object-schema
SYSTEM_OBJECT_SCHEMA =>

, system-object-name ,
SYSTEM_OBJECT_NAME =>

object-type )
OBJECT_TYPE =>

The schema is QSYS2.

system-object-schema A character or graphic string expression that identifies the library that contains
system-object-name.
system-object-name A character or graphic string expression that identifies the object.
object-type A character or graphic string expression that specifies the system object type of
system-object-name.

The result of the function is a table containing rows with the format shown in the following table. All
columns are nullable.
Table 231. OBJECT_PRIVILEGES table function

Column name Data type Description

AUTHORIZATION_USER VARCHAR(10) User profile name. Can contain the following special value.

*PUBLIC This row contains the public authority for the


object.

OBJECT_AUTHORITY VARCHAR(12) The authority that the user has to the object. Contains one of
the following special values:

*ALL Allows all operations on the object except


those that are limited to the owner or
controlled by authorization list management
authority.

*AUTL The public authority specified in the


authorization list used by this object is used.

*CHANGE Allows all operations on the object except


those that are limited to the owner or
controlled by object existence authority,
object alter authority, object reference
authority, and object management authority.

*EXCLUDE All operations on the object are prohibited.

*USE Allows access to the object attributes and


use of the object. The user cannot change
the object.

USER The specific object authorities and data


DEFINED authorities do not match any of the
predefined object authority levels.

AUTHORIZATION_LIST VARCHAR(10) The name of the authorization list if the object is secured by an
authorization list.
Contains null if the object is not secured by an authorization
list.

PRIMARY_GROUP VARCHAR(10) The user who is the primary group for the object.
Returns the null value if there is no primary group for the
object.

OWNER VARCHAR(10) The user profile that owns the object.

Database performance and query optimization 905


Table 231. OBJECT_PRIVILEGES table function (continued)

Column name Data type Description

AUTHORIZATION_LIST_MANAGEMENT VARCHAR(3) The authorization list management authority for


AUTHORIZATION_USER.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_OWNER VARCHAR(3) Indicates whether the AUTHORIZATION_USER for this row is


also the OWNER of the object.

NO AUTHORIZATION_USER is not the owner of the object.

YES AUTHORIZATION_USER is the owner of the object.

OBJECT_OPERATIONAL VARCHAR(3) Indicates the object operational authority for


AUTHORIZATION_USER.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_MANAGEMENT VARCHAR(3) The object management authority for AUTHORIZATION_USER.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_EXISTENCE VARCHAR(3) The object existence authority for AUTHORIZATION_USER.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_ALTER VARCHAR(3) The object alter authority for AUTHORIZATION_USER.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_REFERENCE VARCHAR(3) The object reference authority for AUTHORIZATION_USER.

NO The user does not have this authority.

YES The user has this authority.

DATA_READ VARCHAR(3) The data read authority for AUTHORIZATION_USER.

NO The user does not have this authority.

YES The user has this authority.

DATA_ADD VARCHAR(3) The data add authority for AUTHORIZATION_USER.

NO The user does not have this authority.

YES The user has this authority.

DATA_UPDATE VARCHAR(3) The data update authority for AUTHORIZATION_USER.

NO The user does not have this authority.

YES The user has this authority.

DATA_DELETE VARCHAR(3) The data delete authority for AUTHORIZATION_USER.

NO The user does not have this authority.

YES The user has this authority.

DATA_EXECUTE VARCHAR(3) The data execute authority for AUTHORIZATION_USER.

NO The user does not have this authority.

YES The user has this authority.

906 IBM i: Performance and Query Optimization


Example
Return authority information for the file APPLIB/EMPLOYEE.

SELECT *
FROM TABLE(QSYS2.OBJECT_PRIVILEGES('APPLIB', 'EMPLOYEE', '*FILE'));

OBJECT_PRIVILEGES view
The OBJECT_PRIVILEGES view returns a row for every user authorized to an object, along with their
associated object and data authorities.
The information returned is similar to the information available through the Display Object Authority
(DSPOBJAUT) CL command.
Authorization: All authorized users are returned for an object when at least one of the following is true:
• The caller has *OBJMGT authority.
• The caller is the owner of the object.
• The object is an authorization list.
• The caller is authorized to the QIBM_DB_SECADM function usage identifier.
Otherwise, only authorizations for the caller are returned.
The following table describes the columns in the view. The system name is OBJ_PRIV. The schema is
QSYS2.
Table 232. OBJECT_PRIVILEGES view

Column name System column name Data type Description

OBJECT_SCHEMA OSCHEMA VARCHAR(128) The SQL schema name for this object.

OBJECT_NAME NAME VARCHAR(128) The SQL name of the object.

Nullable For an external procedure or an external function,


the name will be returned when a single procedure
or function exists for that *PGM or *SRVPGM object.
Contains the null value if an SQL name could not be
returned.

SYSTEM_OBJECT_SCHEMA SYS_DNAME VARCHAR(10) The library that contains the object.

SYSTEM_OBJECT_NAME SYS_ONAME VARCHAR(10) The system object name.

OBJECT_TYPE OBJTYPE VARCHAR(8) The system object type.

Database performance and query optimization 907


Table 232. OBJECT_PRIVILEGES view (continued)

Column name System column name Data type Description

SQL_OBJECT_TYPE SQLTYPE VARCHAR(9) The SQL object type. The following values can be
returned.
Nullable
ALIAS The object is an SQL alias.

FUNCTION The object is an SQL function.

INDEX The object is an SQL index.

PACKAGE The object is an SQL package.

PROCEDURE The object is an SQL procedure.

ROUTINE The object is used in SQL by one


or more external functions and/or
external procedures.

SEQUENCE The object is an SQL sequence.

TABLE The object is an SQL table.

TRIGGER The object is an SQL trigger.

TYPE The object is an SQL type.

VARIABLE The object is an SQL global


variable.

VIEW The object is an SQL view.

XSR The object is an XML schema


repository object.

Contains the null value if the object is not an


SQL object or if the user does not have sufficient
authority to the object.

AUTHORIZATION_NAME USER_NAME VARCHAR(10) User profile name. Can contain the following special
value.

*PUBLIC This row contains the public authority


for the object.

OBJECT_AUTHORITY OBJ_AUTH VARCHAR(12) The authority that the user has to the object.
Contains one of the following special values:

*ALL Allows all operations on the


object except those that are
limited to the owner or controlled
by authorization list management
authority.

*AUTL The public authority specified in


the authorization list used by this
object is used.

*CHANGE Allows all operations on the object


except those that are limited
to the owner or controlled by
object existence authority, object
alter authority, object reference
authority, and object management
authority.

*EXCLUDE All operations on the object are


prohibited.

*USE Allows access to the object


attributes and use of the object.
The user cannot change the object.

USER The specific object authorities and


DEFINED data authorities do not match any
of the predefined object authority
levels.

OWNER OWNER VARCHAR(10) The user profile that owns the object.

AUTHORIZATION_LIST AUTL VARCHAR(10) The name of the authorization list if the object is
secured by an authorization list.
Nullable
Contains null if the object is not secured by an
authorization list.

908 IBM i: Performance and Query Optimization


Table 232. OBJECT_PRIVILEGES view (continued)

Column name System column name Data type Description

PRIMARY_GROUP GROUP VARCHAR(10) The user who is the primary group for the object.

Nullable Contains the null value if there is no primary group


for the object.

AUTHORIZATION_LIST_MANAGEMENT AUTL_MGMT VARCHAR(3) The authorization list management authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_OWNER OBJ_OWNER VARCHAR(3) Indicates whether the AUTHORIZATION_NAME for


this row is also the OWNER of the object.

NO AUTHORIZATION_NAME is not the owner of


the object.

YES AUTHORIZATION_NAME is the owner of the


object.

OBJECT_OPERATIONAL OBJOPER VARCHAR(3) Indicates the object operational authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_MANAGEMENT OBJMGT VARCHAR(3) The object management authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_EXISTENCE OBJEXIST VARCHAR(3) The object existence authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_ALTER OBJALTER VARCHAR(3) The object alter authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

OBJECT_REFERENCE OBJREF VARCHAR(3) The object reference authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_READ DATA_READ VARCHAR(3) The data read authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_ADD DATA_ADD VARCHAR(3) The data add authority for AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_UPDATE DATA_UPD VARCHAR(3) The data update authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

Database performance and query optimization 909


Table 232. OBJECT_PRIVILEGES view (continued)

Column name System column name Data type Description

DATA_DELETE DATA_DEL VARCHAR(3) The data delete authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

DATA_EXECUTE DATA_EXEC VARCHAR(3) The data execute authority for


AUTHORIZATION_NAME.

NO The user does not have this authority.

YES The user has this authority.

TEXT_DESCRIPTION TEXT VARCHAR(50) The descriptive text for this object.

Nullable Contains the null value if the object has no text


description or if the user does not have sufficient
authority to the object.

Example
Find user profiles that are publicly accessible.

SELECT *
FROM QSYS2.OBJECT_PRIVILEGES
WHERE SYSTEM_OBJECT_SCHEMA = 'QSYS' AND
OBJECT_TYPE = '*USRPRF' AND
AUTHORIZATION_NAME = '*PUBLIC' AND
OBJECT_AUTHORITY <> '*EXCLUDE';

SECURITY_INFO view
The SECURITY_INFO view returns one row containing information about the IBM i security configuration.
The values returned for the columns in the view are closely related to the values returned by the Display
Security Attributes (DSPSECA) and Display Security Auditing (DSPSECAUD) CL commands and by the
Retrieve Security Attributes (QSYRTVSA) API.
Authorization: The caller must have *AUDIT special authority to see the system values for QAUDCTL,
QAUDLVL, QAUDLVL2, and QCRTOBJAUD.
To see the AUDIT_JOURNAL_RECEIVER_LIBRARY and AUDIT_JOURNAL_RECEIVER values, the caller
must have:
• *OBJOPR and some data authority other than *EXECUTE to journal QSYS/QAUDJRN.
The following table describes the columns in the view. The system name is SEC_INFO. The schema is
QSYS2.
Table 233. SECURITY_INFO view

Column Name System Column Name Data Type Description

SECURITY_LEVEL SECLVL INTEGER The security level that is currently being used by the system.

20 Password security only

30 Password and object security

40 Password, object, and operating system integrity

50 Password, object, and enhanced operating system


integrity

PENDING_SECURITY_LEVEL PENDSECLVL INTEGER The security level that the system will use after the next IPL.

Nullable Contains the null value if the security level will not change after
the next IPL.

910 IBM i: Performance and Query Optimization


Table 233. SECURITY_INFO view (continued)

Column Name System Column Name Data Type Description

PASSWORD_LEVEL PWDLVL INTEGER The password level that is currently being used by the system.

0 User profile passwords with a length of 1-10 characters are


supported.

1 User profile passwords with a length of 1-10 characters


are supported. IBM i NetServer passwords for Windows
95/98/ME clients will be removed from the system.

2 User profile passwords with a length of 1-128 characters


are supported.

3 User profile passwords with a length of 1-128 characters


are supported. IBM i NetServer passwords for Windows
95/98/ME clients will be removed from the system.

PENDING_PASSWORD_LEVEL PENDPWDLVL INTEGER The password level that the system will use after the next IPL.

Nullable Contains the null value if the password level will not change after
the next IPL.

AUDIT_JOURNAL_EXISTS QAUDJRN VARCHAR(3) Whether the security journal QAUDJRN exists.

NO The security journal QAUDJRN does not exist.

YES The security journal QAUDJRN exists.

PASSWORD_CHANGE_BLOCK QPWDCHGBLK VARCHAR(5) The current setting for the block password change
(QPWDCHGBLK) system value.

PASSWORD_EXPIRATION_INTERVAL QPWDEXPITV VARCHAR(6) The current setting for the password expiration interval
(QPWDEXPITV) system value.

PASSWORD_EXPIRATION_WARNING QPWDEXPWRN INTEGER The current setting for the password expiration warning
(QPWDEXPWRN) system value.

PASSWORD_LIMIT_DIGITS QPWDLMTAJC INTEGER The current setting for the limit adjacent digits in password
(QPWDLMTAJC) system value.

PASSWORD_LIMIT_CHARACTERS QPWDLMTCHR VARCHAR(10) The current setting for the limit characters in password
(QPWDLMTCHR) system value.

PASSWORD_LIMIT_REPEAT QPWDLMTREP INTEGER The current setting for the limit repeating characters in
password (QPWDLMTREP) system value.

PASSWORD_LIMIT_POSITIONS QPWDPOSDIF INTEGER The current setting for the limit password character positions
(QPWDPOSDIF) system value.

PASSWORD_REQUIRE_DIGIT QPWDRQDDGT INTEGER The current setting for the require digit in password
(QPWDRQDDGT) system value.

PASSWORD_MAXIMUM_LENGTH QPWDMAXLEN INTEGER The current setting for the maximum password length
(QPWDMAXLEN) system value.

PASSWORD_MINIMUM_LENGTH QPWDMINLEN INTEGER The current setting for the minimum password length
(QPWDMINLEN) system value.

PASSWORD_DUPLICATION QPWDRQDDIF INTEGER The current setting for the duplicate password control
(QPWDRQDDIF) system value.

PASSWORD_RULES QPWDRULES VARCHAR(750) The current setting for the password rules (QPWDRULES) system
value.

PASSWORD_VALIDATION_PROGRAM QPWDVLDPGM VARCHAR(20) The current setting for the password validation program
(QPWDVLDPGM) system value.

CREATE_PUBLIC_AUTHORITY QCRTAUT VARCHAR(8) The current setting for the create default public authority
(QCRTAUT) system value.

CREATE_OBJECT_AUDITING QCRTOBJAUD VARCHAR(7) The current setting for the create object auditing (QCRTOBJAUD)
system value.
Returns the value *NOTAVL if caller does not have *AUDIT
special authority.

MAXIMUM_SIGNON_ATTEMPTS QMAXSIGN VARCHAR(6) The current setting for the maximum sign-on attempts allowed
(QMAXSIGN) system value.

MAXIMUM_SIGNON_ACTION QMAXSGNACN INTEGER The current setting for the action to take for failed sign-on
attempts (QMAXSGNACN) system value.

Database performance and query optimization 911


Table 233. SECURITY_INFO view (continued)

Column Name System Column Name Data Type Description

VERIFY_OBJECT_RESTORE QVFYOBJRST INTEGER The current setting for the verify object on restore
(QVFYOBJRST) system value.

ALLOW_OBJECT_RESTORE QALWOBJRST VARCHAR(150) The current setting for the allow object restore (QALWOBJRST)
system value.

USE_ADOPTED_AUTHORITY QUSEADPAUT VARCHAR(10) The current setting for the use adopted authority (QUSEADPAUT)
system value.

ALLOW_USER_DOMAIN QALWUSRDMN VARCHAR(500) The current setting for the allow user domain objects in libraries
(QALWUSRDMN) system value.

LIMIT_SECOFR_ACCESS QLMTSECOFR INTEGER The current setting for the limit security officer device access
(QLMTSECOFR) system value.

INACTIVE_JOB_TIMEOUT QINACTITV VARCHAR(5) The current setting for the inactive job time-out (QINACTITV)
system value.

INACTIVE_JOB_MESSAGE_QUEUE QINACTMSGQ VARCHAR(20) The current setting for the inactive job message queue
(QINACTMSGQ) system value.

DISCONNECTED_JOB_INTERVAL QDSCJOBITV VARCHAR(5) The current setting for the time interval before disconnected
jobs end (QDSCJOBITV) system value.

AUTOCONFIGURE_DEVICES QAUTOCFG INTEGER The current setting for the autoconfigure devices (QAUTOCFG)
system value.

AUTOCONFIGURE_REMOTE_ QAUTORMT INTEGER The current setting for the autoconfigure of remote controllers
CONTROLLERS (QAUTORMT) system value.

AUDITING_CONTROL QAUDCTL VARCHAR(50) The current setting for the auditing control (QAUDCTL) system
value.
Returns the value *NOTAVL if caller does not have *AUDIT
special authority.

AUDITING_LEVEL QAUDLVL VARCHAR(160) The current setting for the auditing level (QAUDLVL) system
value.
Returns the value *NOTAVL if caller does not have *AUDIT
special authority.

AUDITING_LEVEL_EXTENSION QAUDLVL2 VARCHAR(990) The current setting for the auditing level extension (QAUDLVL2)
system value.
Returns the value *NOTAVL if caller does not have *AUDIT
special authority.

AUDIT_JOURNAL_RECEIVER_ JRNRCV_LIB VARCHAR(10) The name of the library that contains the journal receiver
LIBRARY attached to the security journal.
Nullable
Contains the null value if AUDIT_JOURNAL_EXISTS is NO or if
caller is not authorized.

AUDIT_JOURNAL_RECEIVER JRNRCV VARCHAR(10) The name of the journal receiver attached to the security journal.

Nullable Contains the null value if AUDIT_JOURNAL_EXISTS is NO or if


called is not authorized.

OBJECT_AUTHORITY_COLLECTION_ OBJ_COLL VARCHAR(3) Whether authority collection for objects is active on the
ACTIVE partition. Authority collection for objects is started using
the Start Authority Collection (STRAUTCOL) command with
TYPE(*OBJAUTCOL) and ended using the End Authority
Collection (ENDAUTCOL) command with TYPE(*OBJAUTCOL).

NO Authority collection for objects is not active on the


partition.

YES Authority collection for objects is active for objects with


an authority collection value of *OBJINF.

The authority collection value for an object is set using


the Change Authority Collection (CHGAUTCOL) command with
AUTCOLVAL(*OBJINF).

912 IBM i: Performance and Query Optimization


Table 233. SECURITY_INFO view (continued)

Column Name System Column Name Data Type Description

ALLOW_DIGITAL_CERTIFICATE_ DCM_ADD VARCHAR(3) Whether digital certificates can be added to a certificate store
ADD using the Add Verifier (QYDOADDV, QydoAddVerifier) API, and
whether the password for a certificate store can be reset using
Digital Certificate Manager (DCM).

NO Digital certificates cannot be added to a certificate


store using the QYDOADDV API, and certificate store
passwords cannot be reset using DCM.

YES Digital certificates can be added to a certificate


store using the QYDOADDV API, and certificate store
passwords can be reset using DCM.

The Change SST Security Attributes (CHGSSTSECA) command


can be used to change this attribute.

ALLOW_SECURITY_SYSVAL_ SYSVAL_CHG VARCHAR(3) Whether the security related system values can be changed.
CHANGE
NO The security related system values cannot be changed.

YES The security related system values can be changed.

The Change SST Security Attributes (CHGSSTSECA) command


can be used to change this attribute.

ALLOW_SERVICE_TOOLS_ SSTPWD_CHG VARCHAR(3) Whether a service tools user ID with a default password that is
PASSWORD_CHANGE expired can change its own password.

NO A service tools user ID with a default password that is


expired cannot change its own password.

YES A service tools user ID with a default password that is


expired can change its own password.

The Change SST Security Attributes (CHGSSTSECA) command


can be used to change this attribute.

NEXT_USER_ID NEXT_UID BIGINT The value that will be used the next time a user ID number (UID)
is generated for a user profile.

NEXT_GROUP_ID NEXT_GID BIGINT The value that will be used the next time a group ID number
(GID) is generated for a user profile.

Example
• Return the security and password levels for the system.

SELECT SECURITY_LEVEL, PASSWORD_LEVEL FROM QSYS2.SECURITY_INFO;

SET_COLUMN_ATTRIBUTE procedure
The SET_COLUMN_ATTRIBUTE procedure sets the SECURE attribute for a column so variable values used
for the column cannot be seen in the database monitor or plan cache.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the table, and
• *OBJOPR and *OBJALTER authorities to the table.

SET_COLUMN_ATTRIBUTE (

schema-name , table-name , column-name , attribute )

The schema is SYSPROC.

schema- A character string expression containing the system name of a schema.


name
table-name A character string expression containing the system name of a table.

Database performance and query optimization 913


column- A character string expression containing the system name of a column.
name
attribute A character string expression containing the attribute to set for the column.
Valid values are:

SECURE This column does not contain data that needs to be secured in a database
NO monitor or plan cache
SECURE This column contains data that needs to be secured in a database monitor
YES or plan cache.
All variable values for any query that references this column will not be
visible in a database monitor or plan cache unless the security officer has
started the database monitor or the security officer is accessing the plan
cache. All host variable values will appear as *SECURE when examined
from the monitor and plan cache unless the user is the QSECOFR user.

The secure setting for a column is shown in the SECURE column of the QSYS2/SYSCOLUMNS2 catalog.

Example
Set the credit card column in the ORDERS table so it is secure.

CALL SYSPROC.SET_COLUMN_ATTRIBUTE('LIB1', 'ORDERS', 'CCNBR', 'SECURE YES');

SPECIAL_AUTHORITY_DATA_MART table
The SPECIAL_AUTHORITY_DATA_MART table is a data mart that contains information about special
authorities for users. These authorities can come directly from a user profile or can be obtained through
membership in a group profile.
This data mart is implemented as a materialized query table (MQT). The data in this table is only
populated and refreshed when requested by a user. This is done by using the REFRESH TABLE SQL
statement.
Gathering the special authority information can be a long running task. Consider running the refresh in a
batch job.
Authorization: The table is shipped with public authority of *EXCLUDE.
To refresh the table, the caller must have:
• *EXECUTE authority to the SYSTOOLS library, and
• *OBJMGT, *OBJOPR, *ADD, and *DELETE authority to the SYSTOOLS/SPEC_AUTH file.
To query the table, the caller must have:
• *EXECUTE authority to the SYSTOOLS library, and
• *OBJOPR and *READ authority to the SYSTOOLS/SPEC_AUTH file.
The following table describes the columns in the table. The system name is SPEC_AUTH. The schema is
SYSTOOLS.
Table 234. SPECIAL_AUTHORITY_DATA_MART table

System Column
Column Name Name Data Type Description

AUTHORIZATION_NAME USER_NAME VARCHAR(10) User profile name.

SPECIAL_AUTHORITY SPCAUT VARCHAR(9) Special authority value.

914 IBM i: Performance and Query Optimization


Table 234. SPECIAL_AUTHORITY_DATA_MART table (continued)

System Column
Column Name Name Data Type Description

AUTHORITY_SOURCE AUTHSRC VARCHAR(13) Source of the special authority for this row.

GROUP The authority was obtained through the group


PROFILE profile in the GROUP_PROFILE_NAME column.

USER The authority is part of the user profile


PROFILE definition.

GROUP_PROFILE_NAME GROUP_NAME VARCHAR(10) The group profile that provided the special authority for this row.

Nullable Contains the null value if the special authority was obtained from
the user profile.

STATUS STATUS VARCHAR(10) The status of the user profile.

*DISABLED The user profile is disabled; therefore, the user


cannot sign on.

*ENABLED The user profile is enabled; therefore, the user is


able to sign on.

TEXT_DESCRIPTION TEXT VARCHAR(50) The descriptive text for the user profile.

Nullable Contains the null value if the user profile has no text description.

LAST_USED_DATE LAST_USED DATE The date the user profile was used last.

Nullable Contains the null value if the user profile has not been used.

Examples
• Update the table to contain the current special authority values for all user profiles on the system.

REFRESH TABLE SYSTOOLS.SPECIAL_AUTHORITY_DATA_MART;

• Determine when the table was last refreshed.

SELECT REFRESH_TIME FROM QSYS2.SYSTABLES


WHERE TABLE_SCHEMA = 'SYSTOOLS' AND
TABLE_NAME = 'SPECIAL_AUTHORITY_DATA_MART';

• List all the users who have *ALLOBJ special authority, either directly from their user profile or as part of
a group profile.

SELECT DISTINCT USER_NAME FROM SYSTOOLS.SPECIAL_AUTHORITY_DATA_MART


WHERE SPECIAL_AUTHORITY = '*ALLOBJ';

SQL_CHECK_AUTHORITY scalar function


The SQL_CHECK_AUTHORITY scalar function returns an indication of whether the user is authorized to
query the specified *FILE object.
Authorization: None required.

SQL_CHECK_AUTHORITY ( library-name , file-name )

The schema is QSYS2.

library-name Library name containing the file.


file-name File name for which authority will be examined.

The result of the function is a SMALLINT.


The returned value is:

Database performance and query optimization 915


0 If the user does not have authority to query the file, the object is not a *FILE object, or the object does
not exist.
1 If the user is authorized to query the file.

SQL_CHECK_FUNCTION_USAGE scalar function


The SQL_CHECK_FUNCTION_USAGE scalar function returns an indication of whether the effective user of
the thread is authorized to the specified function usage identifier, either directly, as a member of a group
profile, or through adopted authority.
The validation is performed using the Check User Function Usage (QSYCKUFU,
QsyCheckUserFunctionUsage) API. The usage setting for the user, the user's group, the default usage
value, and the allow *ALLOBJ indicator for the function usage identifier are taken into account.
Authorization: None required.

SQL_CHECK_FUNCTION_USAGE ( function-usage )
FUNCTION_USAGE =>

The schema is QSYS2.

function-usage A character string containing one function usage identifier.

The result of the function is INTEGER.


The function returns the following values:

0 The user is not authorized to the function usage identifier.


1 The user is authorized to the function usage identifier.

Example
• Check whether the current user is authorized to the QIBM_DB_SQLADM function usage identifier.

VALUES QSYS2.SQL_CHECK_FUNCTION_USAGE('QIBM_DB_SQLADM');

SQL_CHECK_SPECIAL_AUTHORITY scalar function


The SQL_CHECK_SPECIAL_AUTHORITY scalar function returns an indication of whether the effective user
of the thread has the specified special authority, either directly, as a member of a group profile, or through
adopted authority.
If the user does not have the special authority, no AF-K audit journal entry is produced.
Authorization: None required.

SQL_CHECK_SPECIAL_AUTHORITY (
SPECIAL_AUTHORITY =>

special-authority )

The schema is QSYS2.

special-authority A character string containing one system special authority value. It must include the
leading * character.

The result of the function is INTEGER.


The function returns the following values:

916 IBM i: Performance and Query Optimization


0 The user does not have the special authority.
1 The user has the special authority.

Example
• Check whether the current user has *JOBCTL special authority.

VALUES QSYS2.SQL_CHECK_SPECIAL_AUTHORITY('*JOBCTL');

USER_INFO view
The USER_INFO view contains information about user profiles.
The USER_INFO_BASIC view returns a subset of this information and is faster.
The values returned for the columns in the view are closely related to the values returned by Retrieve
User Information (QSYRUSRI) API. Refer to the API for more detailed information.
Authorization: The caller must have *OBJOPR and *READ authorities to the *USRPRF. To see a non-
null value for the USER_DEFAULT_PASSWORD column, the caller must have *ALLOBJ and *SECADM
authorities.
The following table describes the columns in the view. The schema is QSYS2.
Table 235. USER_INFO view

Column Name System Column Name Data Type Description

AUTHORIZATION_NAME USER_NAME VARCHAR(10) User profile name.

Nullable

PREVIOUS_SIGNON PRVSIGNON TIMESTAMP The date and time the user last signed on.

Nullable Contains null if the profile has never been used to


sign on.

SIGN_ON_ATTEMPTS_NOT_VALID SIGNONINV INTEGER The number of sign-on attempts that were not
valid since the last successful sign-on.
Nullable

STATUS STATUS VARCHAR(10) The status of the user profile. Contains one of the
following values:
Nullable
*DISABLED The user profile is disabled;
therefore, the user cannot sign
on.

*ENABLED The user profile is enabled;


therefore, the user is able to sign
on.

NETSERVER_DISABLED NETSERVER VARCHAR(3) Whether this user profile is disabled for IBM i
NetServer use.

NO The user profile is not disabled for IBM i


NetServer use.

YES The user profile is disabled for IBM i


NetServer use.

PASSWORD_CHANGE_DATE PWDCHGDAT TIMESTAMP The date the user's password was last changed.

Nullable

NO_PASSWORD_INDICATOR NOPWD VARCHAR(3) Indicates whether *NONE is specified for the


password in the user profile.
Nullable
NO The password in the user profile is not
*NONE.

YES The password in the user profile is


*NONE.

Database performance and query optimization 917


Table 235. USER_INFO view (continued)

Column Name System Column Name Data Type Description

PASSWORD_LEVEL_0_1 PWD_0_1 VARCHAR(3) Indicates whether the user profile has a password
that can be used for a system at QPWDLVL 0 or 1.
Nullable
NO The password cannot be used.

YES The password can be used.

Contains the null value if


NO_PASSWORD_INDICATOR has a value of YES.

PASSWORD_LEVEL_2_3 PWD_2_3 VARCHAR(3) Indicates whether the user profile has a password
that can be used for a system at QPWDLVL 2 or 3.
Nullable
NO The password cannot be used.

YES The password can be used.

Contains the null value if


NO_PASSWORD_INDICATOR has a value of YES.

PASSWORD_EXPIRATION_INTERVAL PWDEXPITV SMALLINT The number of days (from 1 through 366) the
user's password can remain active before it must
Nullable be changed. Can also be one of the following
values:

0 The system value QPWDEXPITV is used to


determine the user's password expiration
interval.

-1 The user's password does not expire


(*NOMAX).

DATE_PASSWORD_EXPIRES PWDEXPDAT TIMESTAMP The date the user's password expires.

Nullable Contains null if the password will not expire.

DAYS_UNTIL_PASSWORD_EXPIRES PWDDAYSEXP INTEGER The number of days until the password will expire.
A value of 0 indicates the password is expired.
Nullable
Contains null if the password will not expire within
the number of days specified by the password
expiration warning (QPWDEXPWRN) system value.

SET_PASSWORD_TO_EXPIRE PWDEXP VARCHAR(3) Indicates whether the user's password is set to


expire, requiring the user to change the password
Nullable when signing on. Contains one of the following
values:

NO The user's password is not set to expire.

YES The user's password is set to expire.

USER_CLASS_NAME USRCLS VARCHAR(10) The user's class name. Contains one of the
following values:
Nullable
*PGMR The user has a class of
programmer.

*SECADM The user has a class of security


administrator.

*SECOFR The user has a class of security


officer.

*SYSOPR The user has a class of system


operator.

*USER The user has a class of end user.

SPECIAL_AUTHORITIES SPCAUT VARCHAR(88) A list of the special authorities the user has. Up to
8 authorities are returned. Each entry is padded
Nullable with blanks to fill 11 characters.
Contains null if the user has no special authorities.

GROUP_PROFILE_NAME GRPPRF VARCHAR(10) The name of the group profile. Contains the value
*NONE if the user does not have a group profile.
Nullable

SUPPLEMENTAL_GROUP_COUNT SUPGRPCNT SMALLINT The number of supplemental groups in the


SUPPLEMENTAL_GROUP_LIST column.

918 IBM i: Performance and Query Optimization


Table 235. USER_INFO view (continued)

Column Name System Column Name Data Type Description

SUPPLEMENTAL_GROUP_LIST SUPGRPLIST VARCHAR(150) A list of supplemental groups for the user profile.
Up to 15 supplemental groups are returned. Each
Nullable entry except for the last one is padded with
blanks to fill 10 characters.
Contains null if the user has no supplemental
groups.

OWNER OWNER VARCHAR(10) This field indicates who is to own objects created
by this user. Contains one of the following values:
Nullable
*GRPPRF The user's group profile owns any
objects the user creates.

*USRPRF The user owns any objects the user


creates.

GROUP_AUTHORITY GRPAUT VARCHAR(10) The authority the user's group profile has to
objects the user creates. Contains one of the
Nullable following values:

*ALL The group profile has all authority


to the objects the user creates.

*CHANGE The group profile has change


authority to the objects the user
creates.

*EXCLUDE The group profile has exclude


authority to the objects the user
creates.

*NONE The group profile has no authority


to the objects the user creates. If
the user does not have a group
profile, this value is returned.

*USE The group profile has use authority


to the objects the user creates.

ASSISTANCE_LEVEL ASTLVL VARCHAR(10) The user interface that the user will use. Contains
one of the following values:
Nullable
*ADVANCED The expert system user
interface.

*BASIC The Operational Assistant user


interface.

*INTERMED The system user interface.

*SYSVAL The system value QASTLVL


determines which user interface
the user is using.

CURRENT_LIBRARY_NAME CURLIB VARCHAR(10) The name of the user's current library. Contains
*CRTDFT if the user does not have a current
Nullable library.

INITIAL_MENU_NAME INLMNU VARCHAR(10) The initial menu for the user. Can contain the
special value *SIGNOFF.
Nullable

INITIAL_MENU_LIBRARY_NAME INLMNULIB VARCHAR(10) The name of the library that the initial menu is in.
Can contain the special value *LIBL.
Nullable
Contains null if the menu name is *SIGNOFF.

INITIAL_PROGRAM_NAME INITPGM VARCHAR(10) The initial program for the user. Contains *NONE
is there is no initial program.
Nullable

INITIAL_PROGRAM_LIBRARY_NAME INITPGMLIB VARCHAR(10) The name of the library that the initial program is
in. Can contain the special value *LIBL.
Nullable
Contains null if the initial program name is *NONE.

Database performance and query optimization 919


Table 235. USER_INFO view (continued)

Column Name System Column Name Data Type Description

LIMIT_CAPABILITIES LMTCPB VARCHAR(10) Indicates whether the user has limited


capabilities. Contains one of the following values:
Nullable
*NO The user is not limited.

*PARTIAL The user cannot change his initial


program or current library.

*YES The user cannot change his initial


menu, initial program, or current
library. The user cannot run
commands from the command line.

TEXT_DESCRIPTION TEXT VARCHAR(50) The descriptive text for the user profile.

Nullable Contains null if the user profile has no text


description.

DISPLAY_SIGNON_INFORMATION DSPSGNINF VARCHAR(10) Indicates whether the sign-on information display


is shown when the user signs on. Contains one of
Nullable the following special values:

*NO The sign-on information display is


not shown when the user signs on.

*SYSVAL The system value QDSPSGNINF


determines if the sign-on
information display is shown when
the user signs on.

*YES The sign-on information display is


shown when the user signs on.

LIMIT_DEVICE_SESSIONS LMTDEVSSN VARCHAR(10) Specifies if the number of device sessions allowed


for a user is limited. Can contain one of the
Nullable following special values:

*NO The user is not limited to a specific


number of device sessions.

*SYSVAL The system value QLMTDEVSSN


determines if the user is limited to
a specific number of device sessions.

*YES The user is limited to one device


session.

KEYBOARD_BUFFERING KBDBUF VARCHAR(10) The keyboard buffering value that is used when a
job is initialized for this user. Contains one of the
Nullable following special values:

*NO The type-ahead and attention-


key buffering options are not
on.

*SYSVAL The system value QKBDBUF


determines the keyboard
buffering value for this user.

*TYPEAHEAD The type-ahead option is on,


but the attention-key buffering
option is not.

*YES The type-ahead and attention-


key buffering options are both
on.

MAXIMUM_ALLOWED_STORAGE MAXSTGLRG BIGINT The maximum amount of auxiliary storage


(in kilobytes) that can be assigned to store
Nullable permanent objects owned by the user. Contains
null if the user has no maximum storage.

STORAGE_USED STGUSED BIGINT The amount of auxiliary storage (in kilobytes)


occupied by this user's owned objects on
Nullable *SYSBAS. The QSYS2.USER_STORAGE catalog
should be used to determine the storage
consumed on all ASPs.

920 IBM i: Performance and Query Optimization


Table 235. USER_INFO view (continued)

Column Name System Column Name Data Type Description

HIGHEST_SCHEDULING_PRIORITY PTYLMT CHAR(1) The highest scheduling priority the user is allowed
to have for each job submitted to the system.
Nullable

JOB_DESCRIPTION_NAME JOBD VARCHAR(10) The name of the job description used for jobs that
start through subsystem work station entries.
Nullable

JOB_DESCRIPTION_LIBRARY_NAME JOBDLIB VARCHAR(10) Job description library name. Can contain the
special value *LIBL.
Nullable

ACCOUNTING_CODE ACGCDE VARCHAR(15) The accounting code that is associated with this
user.
Nullable
Contains null if there is no accounting code.

MESSAGE_QUEUE_NAME MSGQ VARCHAR(10) The name of the message queue that is used by
this user.
Nullable

MESSAGE_QUEUE_LIBRARY_NAME MSGQLIB VARCHAR(10) The name of the library the message queue is in.
Can contain the special value *LIBL.
Nullable

MESSAGE_QUEUE_DELIVERY_METHOD DLVRY VARCHAR(10) How the messages are delivered to the message
queue used by the user. Contains one of the
Nullable following values:

*BREAK The job to which the message queue


is assigned is interrupted when a
message arrives on the message
queue.

*DFT Messages requiring replies are


answered with their default reply.

*HOLD The messages are held in the


message queue until they are
requested by the user or program.

*NOTIFY The job to which the message


queue is assigned is notified when
a message arrives on the message
queue.

MESSAGE_QUEUE_SEVERITY SEV SMALLINT The lowest severity that a message can have and
still be delivered to a user in break or notify mode
Nullable

OUTPUT_QUEUE_NAME OUTQ VARCHAR(10) The output queue used by this user. Can contain
one of the following special values:
Nullable
*DEV An output queue with the same
name as the device specified in the
printer device parameter is used by
the user.

*WRKSTN The output queue assigned to the


user's work station is used.

OUTPUT_QUEUE_LIBRARY_NAME OUTQLIB VARCHAR(10) The name of the library where the output queue is
located.
Nullable
Contains null if the output queue name is *DEV or
*WRKSTN.

PRINT_DEVICE PRTDEV VARCHAR(10) The printer used to print for this user. Can contain
one of the following special values:
Nullable
*SYSVAL The default system printer
specified in the system value
QPRTDEV is used.

*WRKSTN The printer assigned to the user's


work station is used.

Database performance and query optimization 921


Table 235. USER_INFO view (continued)

Column Name System Column Name Data Type Description

SPECIAL_ENVIRONMENT SPCENV VARCHAR(10) The special environment the user operates in


after signing on. Contains one of the following
Nullable special values:

*NONE The user operates in the IBM i


environment.

*SYSVAL The system value QSPCENV is used


to determine the user's special
environment.

*S36 The user operates in the System/36


environment.

ATTENTION_KEY_HANDLING_ ATNPGM VARCHAR(10) The attention key handling program for this user.
PROGRAM_NAME Can contain one of the following special values:
Nullable
*NONE No Attention-key-handling program
is used.

*SYSVAL The system value QATNPGM


determines the user's Attention-key-
handling program.

ATTENTION_KEY_HANDLING_ ATNPGMLIB VARCHAR(10) The name of the library where the program is
PROGRAM_LIBRARY_NAME located. Can contain the special value *LIBL.
Nullable
Contains null if the attention key handling
program is *NONE or *SYSVAL.

LANGUAGE_ID LANGID VARCHAR(10) The language ID used by the system for this user.
Can contain the following special value:
Nullable
*SYSVAL The system value QLANGID is used
to determine the user's language ID.

COUNTRY_OR_REGION_ID CNTRYID VARCHAR(10) Country or region ID. Can contain the following
special value:
Nullable
*SYSVAL The system value QCNTRYID is used
to determine the user's country or
region ID.

CHARACTER_CODE_SET_ID CCSID VARCHAR(6) The CCSID for the user. Can contain the following
special value:
Nullable
QCCSID The system value QCCSID is used to
determine the user's character code
set ID.

USER_OPTIONS USROPT VARCHAR(77) A list of the options for users to customize their
environment. Up to 7 options are returned. Each
Nullable entry is padded with blanks to fill 11 characters.
Contains null if there are no user options.

SORT_SEQUENCE_TABLE_NAME SRTSEQ VARCHAR(10) The name of the sort sequence table used
for string comparisons. Can contain one of the
Nullable following special values:

*HEX The hexadecimal values of


the characters are used to
determine the sort sequence.

*LANGIDSHR A shared-weight sort table


associated with the language
specified.

*LANGIDUNQ A unique-weight sort table


associated with the language
specified.

*SYSVAL The system value QSRTSEQ.

SORT_SEQUENCE_TABLE_LIBRARY_NAME SRTSEQLIB VARCHAR(10) The name of the library that is used to locate the
sort sequence table.
Nullable
Contains null if the sort sequence table is a
special value.

922 IBM i: Performance and Query Optimization


Table 235. USER_INFO view (continued)

Column Name System Column Name Data Type Description

OBJECT_AUDITING_VALUE OBJAUD VARCHAR(10) The object auditing value for this user. Contains
one of the following values:
Nullable
*ALL Object read and change operations
are audited for the current user
if the object's auditing value is
*USRPRF.

*CHANGE Object changes are audited for the


current user if the object's auditing
value is *USRPRF.

*NONE No additional object auditing is


done for the current user.

*NOTAVL The user is not allowed to retrieve


the object auditing value.

USER_ACTION_AUDIT_LEVEL AUDLVL VARCHAR(363) The action audit values for this user. Up to 31
options are returned. Each entry is padded with
Nullable blanks to fill 11 characters.
Contains null if there are no action values or if the
caller is not authorized to retrieve the action audit
level.

GROUP_AUTHORITY_TYPE GRPAUTTYP VARCHAR(10) The type of authority the user's group profile has
to objects the user creates. Contains one of the
Nullable following special values:

*PGP The group profile will be the


primary group for objects the user
creates.

*PRIVATE The group profile has a private


authority to the objects the user
creates. If the user does not have a
group profile, this value is returned.

USER_ID_NUMBER UID BIGINT The user ID number for the user profile.

Nullable

GROUP_ID_NUMBER GID BIGINT The group ID number for the user profile. The
value 0 is returned if the user has no group ID
Nullable number.

LOCALE_JOB_ATTRIBUTES SETJOBATR VARCHAR(88) A list of the job attributes that are taken from the
user's locale path. This column contains a list of
Nullable up to 8 items. Each entry is padded with blanks to
fill 11 characters.

GROUP_MEMBER_INDICATOR GRPMBR VARCHAR(3) Whether this user is a group that has members.
Contains one of the following values:
Nullable
NO The user is not a group, or is a group but
does not have any members.

YES The user is a group that has members.

DIGITAL_CERTIFICATE_INDICATOR DCIND VARCHAR(3) Whether there are digital certificates associated


with this user. Contains one of the following
Nullable values:

NO There are no digital certificates


associated with this user.

YES There is at least one digital certificate


associated with this user.

Database performance and query optimization 923


Table 235. USER_INFO view (continued)

Column Name System Column Name Data Type Description

CHARACTER_IDENTIFIER_CONTROL CHRIDCTL VARCHAR(10) The character identifier control for the user. Can
contain the following special values:
Nullable
*DEVD The *DEVD special value
performs the same function as on
the CHRID command parameter
for display files, printer files, and
panel groups.

*JOBCCSID The *JOBCCSID special value


performs the same function as on
the CHRID command parameter
for display files, printer files, and
panel groups.

*SYSVAL The value QCHRIDCTL system


value will be used to determine
the CHRID control for this user.

LOCAL_PASSWORD_MANAGEMENT LCLPWDMGT VARCHAR(3) Indicates if password is managed locally. Contains


one of the following values:
Nullable
NO The password is not managed locally.

YES The password is managed locally.

BLOCK_PASSWORD_CHANGE PWDCHGBLK VARCHAR(10) Specifies the time period, in hours, during which
a password is blocked from being changed
Nullable following the prior successful password change
operation. Can contain one of the following
special values:

*NONE The password can be changed at any


time.

*SYSVAL The system value QPWDCHGBLK is


used to determine the password
change limit.

USER_ENTITLEMENT_REQUIRED ENTITLERQD VARCHAR(3) Whether a user entitlement is required for this


user profile. Contains one of the following values:
Nullable
NO A user entitlement is not required for this
user profile.

YES A user entitlement is required for this user


profile.

USER_EXPIRATION_INTERVAL USREXPITV SMALLINT The number of days (from 1 through 366) before
the user profile is automatically disabled. The
Nullable value 0 is returned if no expiration interval is
defined.

USER_EXPIRATION_DATE USREXPDATE TIMESTAMP The date when the user profile expires and is
automatically disabled or deleted.
Nullable
Contains null if the user profile will not expire.

USER_EXPIRATION_ACTION ACTION VARCHAR(8) The action that will occur when the user profile
has expired. Contains one of the following values:
Nullable
*DELETE The user profile will be deleted. If
the user profile cannot be deleted,
it will be disabled.

*DISABLE The user profile will be disabled.

*NONE The user profile will not expire.

HOME_DIRECTORY HOMEDIR VARGRAPHIC(1024) The home directory for this user profile.
CCSID 1200

Nullable

924 IBM i: Performance and Query Optimization


Table 235. USER_INFO view (continued)

Column Name System Column Name Data Type Description

LOCALE_PATH_NAME LOCALE VARGRAPHIC(1024) The locale path name that is assigned to the user
CCSID 1200 profile when a job is started. Can contain one of
the following special values:
Nullable
*C The C locale path name is assigned.

*NONE No locale path name is assigned.

*POSIX The POSIX locale path name is


assigned.

*SYSVAL The QLOCALE system value is used


to determine the locale path name.

USER_DEFAULT_PASSWORD DFTPWD VARCHAR(3) The password is the default password.

Nullable NO The password is not the default password.

YES The password appears to be the default


password since it matches the user profile
name.

Contains null if not authorized to view this


information.

USER_OWNER USER_OWNER VARCHAR(10) The user profile that owns this user profile.

Nullable

USER_CREATOR CREATOR VARCHAR(10) The user profile that created this user profile.

Nullable

SIZE SIZE DECIMAL(15,0) Size of the user profile, in bytes.

Nullable

CREATION_TIMESTAMP TIMESTAMP TIMESTAMP Timestamp of when the user profile was created.

Nullable

LAST_USED_TIMESTAMP LASTUSED TIMESTAMP The date the user profile was used last. The time
portion of the timestamp will always be 0.
Nullable

DAYS_USED_COUNT DAYSUSED INTEGER The number of days the user profile has been
used on the system.
Nullable

LAST_RESET_TIMESTAMP LASTRESET TIMESTAMP The date when the days used count was last reset
to zero. The time portion of the timestamp will
Nullable always be 0.

AUTHORITY_COLLECTION_ACTIVE AUTCOLACT VARCHAR(3) Whether authority collection is active for this user.

NO Authority collection is not active for this


user.

YES Authority collection is active for this user.

AUTHORITY_COLLECTION_REPOSITORY_ AUTCOLREP VARCHAR(3) Whether an authority collection repository exists


EXISTS for this user.

NO An authority collection repository does


not exist for this user.

YES An authority collection repository exists


for this user.

PASE_SHELL_PATH SHELL_PATH VARCHAR(1024) Path to the user's PASE shell. If


CCSID 1208 AUTHORIZATION_NAME is QSYS, this column
Nullable contains the default shell path used for all user
profiles that have not had a value explicitly set.
Returns the null value if a value has not been
set using the QSYS2.SET_PASE_SHELL_INFO
procedure.

Example

Database performance and query optimization 925


Determine which users are having trouble signing on.

SELECT * FROM QSYS2.USER_INFO


WHERE SIGN_ON_ATTEMPTS_NOT_VALID > 0

USER_INFO_BASIC view
The USER_INFO_BASIC view contains information about user profiles.
This view returns a subset of columns that are returned by the USER_INFO view. It does
not return: USER_OWNER , USER_CREATOR, SIZE, CREATION_TIMESTAMP, LAST_USED_TIMESTAMP,
DAYS_USED_COUNT, or LAST_RESET_TIMESTAMP. USER_INFO_BASIC typically performs much better
than USER_INFO.
The values returned for the columns in the view are closely related to the values returned by Retrieve
User Information (QSYRUSRI) API. Refer to the API for more detailed information.
Authorization: The caller must have *OBJOPR and *READ authorities to the *USRPRF. To see a non-
null value for the USER_DEFAULT_PASSWORD column, the caller must have *ALLOBJ and *SECADM
authorities.
The following table describes the columns in the view. The system name is USER_INFOB. The schema is
QSYS2.
Table 236. USER_INFO_BASIC view

Column Name System Column Name Data Type Description

AUTHORIZATION_NAME USER_NAME VARCHAR(10) User profile name.

Nullable

PREVIOUS_SIGNON PRVSIGNON TIMESTAMP The date and time the user last signed on.

Nullable Contains null if the profile has never been used to


sign on.

SIGN_ON_ATTEMPTS_NOT_VALID SIGNONINV INTEGER The number of sign-on attempts that were not
valid since the last successful sign-on.
Nullable

STATUS STATUS VARCHAR(10) The status of the user profile. Contains one of the
following values:
Nullable
*DISABLED The user profile is disabled;
therefore, the user cannot sign
on.

*ENABLED The user profile is enabled;


therefore, the user is able to sign
on.

NETSERVER_DISABLED NETSERVER VARCHAR(3) Whether this user profile is disabled for IBM i
NetServer use.

NO The user profile is not disabled for IBM i


NetServer use.

YES The user profile is disabled for IBM i


NetServer use.

PASSWORD_CHANGE_DATE PWDCHGDAT TIMESTAMP The date the user's password was last changed.

Nullable

NO_PASSWORD_INDICATOR NOPWD VARCHAR(3) Indicates whether *NONE is specified for the


password in the user profile.
Nullable
NO The password in the user profile is not
*NONE.

YES The password in the user profile is


*NONE.

926 IBM i: Performance and Query Optimization


Table 236. USER_INFO_BASIC view (continued)

Column Name System Column Name Data Type Description

PASSWORD_LEVEL_0_1 PWD_0_1 VARCHAR(3) Indicates whether the user profile has a password
that can be used for a system at QPWDLVL 0 or 1.
Nullable
NO The password cannot be used.

YES The password can be used.

Contains the null value if


NO_PASSWORD_INDICATOR has a value of YES.

PASSWORD_LEVEL_2_3 PWD_2_3 VARCHAR(3) Indicates whether the user profile has a password
that can be used for a system at QPWDLVL 2 or 3.
Nullable
NO The password cannot be used.

YES The password can be used.

Contains the null value if


NO_PASSWORD_INDICATOR has a value of YES.

PASSWORD_EXPIRATION_INTERVAL PWDEXPITV SMALLINT The number of days (from 1 through 366) the
user's password can remain active before it must
Nullable be changed. Can also be one of the following
values:

0 The system value QPWDEXPITV is used to


determine the user's password expiration
interval.

-1 The user's password does not expire


(*NOMAX).

DATE_PASSWORD_EXPIRES PWDEXPDAT TIMESTAMP The date the user's password expires.

Nullable Contains null if the password will not expire.

DAYS_UNTIL_PASSWORD_EXPIRES PWDDAYSEXP INTEGER The number of days until the password will expire.
A value of 0 indicates the password is expired.
Nullable
Contains null if the password will not expire within
the number of days specified by the password
expiration warning (QPWDEXPWRN) system value.

SET_PASSWORD_TO_EXPIRE PWDEXP VARCHAR(3) Indicates whether the user's password is set to


expire, requiring the user to change the password
Nullable when signing on. Contains one of the following
values:

NO The user's password is not set to expire.

YES The user's password is set to expire.

USER_CLASS_NAME USRCLS VARCHAR(10) The user's class name. Contains one of the
following values:
Nullable
*PGMR The user has a class of
programmer.

*SECADM The user has a class of security


administrator.

*SECOFR The user has a class of security


officer.

*SYSOPR The user has a class of system


operator.

*USER The user has a class of end user.

SPECIAL_AUTHORITIES SPCAUT VARCHAR(88) A list of the special authorities the user has. Up to
8 authorities are returned. Each entry is padded
Nullable with blanks to fill 11 characters.
Contains null if the user has no special authorities.

GROUP_PROFILE_NAME GRPPRF VARCHAR(10) The name of the group profile. Contains the value
*NONE if the user does not have a group profile.
Nullable

SUPPLEMENTAL_GROUP_COUNT SUPGRPCNT SMALLINT The number of supplemental groups in the


SUPPLEMENTAL_GROUP_LIST column.

Database performance and query optimization 927


Table 236. USER_INFO_BASIC view (continued)

Column Name System Column Name Data Type Description

SUPPLEMENTAL_GROUP_LIST SUPGRPLIST VARCHAR(150) A list of supplemental groups for the user profile.
Up to 15 supplemental groups are returned. Each
Nullable entry except for the last one is padded with
blanks to fill 10 characters.
Contains null if the user has no supplemental
groups.

OWNER OWNER VARCHAR(10) This field indicates who is to own objects created
by this user. Contains one of the following values:
Nullable
*GRPPRF The user's group profile owns any
objects the user creates.

*USRPRF The user owns any objects the user


creates.

GROUP_AUTHORITY GRPAUT VARCHAR(10) The authority the user's group profile has to
objects the user creates. Contains one of the
Nullable following values:

*ALL The group profile has all authority


to the objects the user creates.

*CHANGE The group profile has change


authority to the objects the user
creates.

*EXCLUDE The group profile has exclude


authority to the objects the user
creates.

*NONE The group profile has no authority


to the objects the user creates. If
the user does not have a group
profile, this value is returned.

*USE The group profile has use authority


to the objects the user creates.

ASSISTANCE_LEVEL ASTLVL VARCHAR(10) The user interface that the user will use. Contains
one of the following values:
Nullable
*ADVANCED The expert system user
interface.

*BASIC The Operational Assistant user


interface.

*INTERMED The system user interface.

*SYSVAL The system value QASTLVL


determines which user interface
the user is using.

CURRENT_LIBRARY_NAME CURLIB VARCHAR(10) The name of the user's current library. Contains
*CRTDFT if the user does not have a current
Nullable library.

INITIAL_MENU_NAME INLMNU VARCHAR(10) The initial menu for the user. Can contain the
special value *SIGNOFF.
Nullable

INITIAL_MENU_LIBRARY_NAME INLMNULIB VARCHAR(10) The name of the library that the initial menu is in.
Can contain the special value *LIBL.
Nullable
Contains null if the menu name is *SIGNOFF.

INITIAL_PROGRAM_NAME INITPGM VARCHAR(10) The initial program for the user. Contains *NONE
is there is no initial program.
Nullable

INITIAL_PROGRAM_LIBRARY_NAME INITPGMLIB VARCHAR(10) The name of the library that the initial program is
in. Can contain the special value *LIBL.
Nullable
Contains null if the initial program name is *NONE.

928 IBM i: Performance and Query Optimization


Table 236. USER_INFO_BASIC view (continued)

Column Name System Column Name Data Type Description

LIMIT_CAPABILITIES LMTCPB VARCHAR(10) Indicates whether the user has limited


capabilities. Contains one of the following values:
Nullable
*NO The user is not limited.

*PARTIAL The user cannot change his initial


program or current library.

*YES The user cannot change his initial


menu, initial program, or current
library. The user cannot run
commands from the command line.

TEXT_DESCRIPTION TEXT VARCHAR(50) The descriptive text for the user profile.

Nullable Contains null if the user profile has no text


description.

DISPLAY_SIGNON_INFORMATION DSPSGNINF VARCHAR(10) Indicates whether the sign-on information display


is shown when the user signs on. Contains one of
Nullable the following special values:

*NO The sign-on information display is


not shown when the user signs on.

*SYSVAL The system value QDSPSGNINF


determines if the sign-on
information display is shown when
the user signs on.

*YES The sign-on information display is


shown when the user signs on.

LIMIT_DEVICE_SESSIONS LMTDEVSSN VARCHAR(10) Specifies if the number of device sessions allowed


for a user is limited. Can contain one of the
Nullable following special values:

*NO The user is not limited to a specific


number of device sessions.

*SYSVAL The system value QLMTDEVSSN


determines if the user is limited to
a specific number of device sessions.

*YES The user is limited to one device


session.

KEYBOARD_BUFFERING KBDBUF VARCHAR(10) The keyboard buffering value that is used when a
job is initialized for this user. Contains one of the
Nullable following special values:

*NO The type-ahead and attention-


key buffering options are not
on.

*SYSVAL The system value QKBDBUF


determines the keyboard
buffering value for this user.

*TYPEAHEAD The type-ahead option is on,


but the attention-key buffering
option is not.

*YES The type-ahead and attention-


key buffering options are both
on.

MAXIMUM_ALLOWED_STORAGE MAXSTGLRG BIGINT The maximum amount of auxiliary storage


(in kilobytes) that can be assigned to store
Nullable permanent objects owned by the user. Contains
null if the user has no maximum storage.

STORAGE_USED STGUSED BIGINT The amount of auxiliary storage (in kilobytes)


occupied by this user's owned objects on
Nullable *SYSBAS. The QSYS2.USER_STORAGE catalog
should be used to determine the storage
consumed on all ASPs.

Database performance and query optimization 929


Table 236. USER_INFO_BASIC view (continued)

Column Name System Column Name Data Type Description

HIGHEST_SCHEDULING_PRIORITY PTYLMT CHAR(1) The highest scheduling priority the user is allowed
to have for each job submitted to the system.
Nullable

JOB_DESCRIPTION_NAME JOBD VARCHAR(10) The name of the job description used for jobs that
start through subsystem work station entries.
Nullable

JOB_DESCRIPTION_LIBRARY_NAME JOBDLIB VARCHAR(10) Job description library name. Can contain the
special value *LIBL.
Nullable

ACCOUNTING_CODE ACGCDE VARCHAR(15) The accounting code that is associated with this
user.
Nullable
Contains null if there is no accounting code.

MESSAGE_QUEUE_NAME MSGQ VARCHAR(10) The name of the message queue that is used by
this user.
Nullable

MESSAGE_QUEUE_LIBRARY_NAME MSGQLIB VARCHAR(10) The name of the library the message queue is in.
Can contain the special value *LIBL.
Nullable

MESSAGE_QUEUE_DELIVERY_METHOD DLVRY VARCHAR(10) How the messages are delivered to the message
queue used by the user. Contains one of the
Nullable following values:

*BREAK The job to which the message queue


is assigned is interrupted when a
message arrives on the message
queue.

*DFT Messages requiring replies are


answered with their default reply.

*HOLD The messages are held in the


message queue until they are
requested by the user or program.

*NOTIFY The job to which the message


queue is assigned is notified when
a message arrives on the message
queue.

MESSAGE_QUEUE_SEVERITY SEV SMALLINT The lowest severity that a message can have and
still be delivered to a user in break or notify mode
Nullable

OUTPUT_QUEUE_NAME OUTQ VARCHAR(10) The output queue used by this user. Can contain
one of the following special values:
Nullable
*DEV An output queue with the same
name as the device specified in the
printer device parameter is used by
the user.

*WRKSTN The output queue assigned to the


user's work station is used.

OUTPUT_QUEUE_LIBRARY_NAME OUTQLIB VARCHAR(10) The name of the library where the output queue is
located.
Nullable
Contains null if the output queue name is *DEV or
*WRKSTN.

PRINT_DEVICE PRTDEV VARCHAR(10) The printer used to print for this user. Can contain
one of the following special values:
Nullable
*SYSVAL The default system printer
specified in the system value
QPRTDEV is used.

*WRKSTN The printer assigned to the user's


work station is used.

930 IBM i: Performance and Query Optimization


Table 236. USER_INFO_BASIC view (continued)

Column Name System Column Name Data Type Description

SPECIAL_ENVIRONMENT SPCENV VARCHAR(10) The special environment the user operates in


after signing on. Contains one of the following
Nullable special values:

*NONE The user operates in the IBM i


environment.

*SYSVAL The system value QSPCENV is used


to determine the user's special
environment.

*S36 The user operates in the System/36


environment.

ATTENTION_KEY_HANDLING_ ATNPGM VARCHAR(10) The attention key handling program for this user.
PROGRAM_NAME Can contain one of the following special values:
Nullable
*NONE No Attention-key-handling program
is used.

*SYSVAL The system value QATNPGM


determines the user's Attention-key-
handling program.

ATTENTION_KEY_HANDLING_ ATNPGMLIB VARCHAR(10) The name of the library where the program is
PROGRAM_LIBRARY_NAME located. Can contain the special value *LIBL.
Nullable
Contains null if the attention key handling
program is *NONE or *SYSVAL.

LANGUAGE_ID LANGID VARCHAR(10) The language ID used by the system for this user.
Can contain the following special value:
Nullable
*SYSVAL The system value QLANGID is used
to determine the user's language ID.

COUNTRY_OR_REGION_ID CNTRYID VARCHAR(10) Country or region ID. Can contain the following
special value:
Nullable
*SYSVAL The system value QCNTRYID is used
to determine the user's country or
region ID.

CHARACTER_CODE_SET_ID CCSID VARCHAR(6) The CCSID for the user. Can contain the following
special value:
Nullable
QCCSID The system value QCCSID is used to
determine the user's character code
set ID.

USER_OPTIONS USROPT VARCHAR(77) A list of the options for users to customize their
environment. Up to 7 options are returned. Each
Nullable entry is padded with blanks to fill 11 characters.
Contains null if there are no user options.

SORT_SEQUENCE_TABLE_NAME SRTSEQ VARCHAR(10) The name of the sort sequence table used
for string comparisons. Can contain one of the
Nullable following special values:

*HEX The hexadecimal values of


the characters are used to
determine the sort sequence.

*LANGIDSHR A shared-weight sort table


associated with the language
specified.

*LANGIDUNQ A unique-weight sort table


associated with the language
specified.

*SYSVAL The system value QSRTSEQ.

SORT_SEQUENCE_TABLE_LIBRARY_NAME SRTSEQLIB VARCHAR(10) The name of the library that is used to locate the
sort sequence table.
Nullable
Contains null if the sort sequence table is a
special value.

Database performance and query optimization 931


Table 236. USER_INFO_BASIC view (continued)

Column Name System Column Name Data Type Description

OBJECT_AUDITING_VALUE OBJAUD VARCHAR(10) The object auditing value for this user. Contains
one of the following values:
Nullable
*ALL Object read and change operations
are audited for the current user
if the object's auditing value is
*USRPRF.

*CHANGE Object changes are audited for the


current user if the object's auditing
value is *USRPRF.

*NONE No additional object auditing is


done for the current user.

*NOTAVL The user is not allowed to retrieve


the object auditing value.

USER_ACTION_AUDIT_LEVEL AUDLVL VARCHAR(363) The action audit values for this user. Up to 31
options are returned. Each entry is padded with
Nullable blanks to fill 11 characters.
Contains null if there are no action values or if the
caller is not authorized to retrieve the action audit
level.

GROUP_AUTHORITY_TYPE GRPAUTTYP VARCHAR(10) The type of authority the user's group profile has
to objects the user creates. Contains one of the
Nullable following special values:

*PGP The group profile will be the


primary group for objects the user
creates.

*PRIVATE The group profile has a private


authority to the objects the user
creates. If the user does not have a
group profile, this value is returned.

USER_ID_NUMBER UID BIGINT The user ID number for the user profile.

Nullable

GROUP_ID_NUMBER GID BIGINT The group ID number for the user profile. The
value 0 is returned if the user has no group ID
Nullable number.

LOCALE_JOB_ATTRIBUTES SETJOBATR VARCHAR(88) A list of the job attributes that are taken from the
user's locale path. This column contains a list of
Nullable up to 8 items. Each entry is padded with blanks to
fill 11 characters.

GROUP_MEMBER_INDICATOR GRPMBR VARCHAR(3) Whether this user is a group that has members.
Contains one of the following values:
Nullable
NO The user is not a group, or is a group but
does not have any members.

YES The user is a group that has members.

DIGITAL_CERTIFICATE_INDICATOR DCIND VARCHAR(3) Whether there are digital certificates associated


with this user. Contains one of the following
Nullable values:

NO There are no digital certificates


associated with this user.

YES There is at least one digital certificate


associated with this user.

932 IBM i: Performance and Query Optimization


Table 236. USER_INFO_BASIC view (continued)

Column Name System Column Name Data Type Description

CHARACTER_IDENTIFIER_CONTROL CHRIDCTL VARCHAR(10) The character identifier control for the user. Can
contain the following special values:
Nullable
*DEVD The *DEVD special value
performs the same function as on
the CHRID command parameter
for display files, printer files, and
panel groups.

*JOBCCSID The *JOBCCSID special value


performs the same function as on
the CHRID command parameter
for display files, printer files, and
panel groups.

*SYSVAL The value QCHRIDCTL system


value will be used to determine
the CHRID control for this user.

LOCAL_PASSWORD_MANAGEMENT LCLPWDMGT VARCHAR(3) Indicates if password is managed locally. Contains


one of the following values:
Nullable
NO The password is not managed locally.

YES The password is managed locally.

BLOCK_PASSWORD_CHANGE PWDCHGBLK VARCHAR(10) Specifies the time period, in hours, during which
a password is blocked from being changed
Nullable following the prior successful password change
operation. Can contain one of the following
special values:

*NONE The password can be changed at any


time.

*SYSVAL The system value QPWDCHGBLK is


used to determine the password
change limit.

USER_ENTITLEMENT_REQUIRED ENTITLERQD VARCHAR(3) Whether a user entitlement is required for this


user profile. Contains one of the following values:
Nullable
NO A user entitlement is not required for this
user profile.

YES A user entitlement is required for this user


profile.

USER_EXPIRATION_INTERVAL USREXPITV SMALLINT The number of days (from 1 through 366) before
the user profile is automatically disabled. The
Nullable value 0 is returned if no expiration interval is
defined.

USER_EXPIRATION_DATE USREXPDATE TIMESTAMP The date when the user profile expires and is
automatically disabled or deleted.
Nullable
Contains null if the user profile will not expire.

USER_EXPIRATION_ACTION ACTION VARCHAR(8) The action that will occur when the user profile
has expired. Contains one of the following values:
Nullable
*DELETE The user profile will be deleted. If
the user profile cannot be deleted,
it will be disabled.

*DISABLE The user profile will be disabled.

*NONE The user profile will not expire.

HOME_DIRECTORY HOMEDIR VARGRAPHIC(1024) The home directory for this user profile.
CCSID 1200

Nullable

Database performance and query optimization 933


Table 236. USER_INFO_BASIC view (continued)

Column Name System Column Name Data Type Description

LOCALE_PATH_NAME LOCALE VARGRAPHIC(1024) The locale path name that is assigned to the user
CCSID 1200 profile when a job is started. Can contain one of
the following special values:
Nullable
*C The C locale path name is assigned.

*NONE No locale path name is assigned.

*POSIX The POSIX locale path name is


assigned.

*SYSVAL The QLOCALE system value is used


to determine the locale path name.

USER_DEFAULT_PASSWORD DFTPWD VARCHAR(3) The password is the default password.

Nullable NO The password is not the default password.

YES The password appears to be the default


password since it matches the user profile
name.

Contains null if not authorized to view this


information.

AUTHORITY_COLLECTION_ACTIVE AUTCOLACT VARCHAR(3) Whether authority collection is active for this user.

NO Authority collection is not active for this


user.

YES Authority collection is active for this user.

AUTHORITY_COLLECTION_REPOSITORY_ AUTCOLREP VARCHAR(3) Whether an authority collection repository exists


EXISTS for this user.

NO An authority collection repository does


not exist for this user.

YES An authority collection repository exists


for this user.

PASE_SHELL_PATH SHELL_PATH VARCHAR(1024) Path to the user's PASE shell. If


CCSID 1208 AUTHORIZATION_NAME is QSYS, this column
Nullable contains the default shell path used for all user
profiles that have not had a value explicitly set.
Returns the null value if a value has not been
set using the QSYS2.SET_PASE_SHELL_INFO
procedure.

Example
Determine which users have *ALLOBJ special authority.

SELECT * FROM QSYS2.USER_INFO_BASIC


WHERE SPECIAL_AUTHORITIES LIKE '%*ALLOBJ%';

Spool Services
These views and functions provide information about spooled files.

DELETE_OLD_SPOOLED_FILES procedure
The DELETE_OLD_SPOOLED_FILES procedure deletes spooled files according to filtering criteria. It can
optionally return a preview of the files that meet the filtering criteria without performing the delete.
Authorization: See Note below.

934 IBM i: Performance and Query Optimization


DELETE_OLD_SPOOLED_FILES (

delete-older-than
DELETE_OLDER_THAN =>

, p-output-queue-library-name
P_OUTPUT_QUEUE_LIBRARY_NAME =>

, p-output-queue-name
P_OUTPUT_QUEUE_NAME =>

, p-user-name
P_USER_NAME =>

)
, preview
PREVIEW =>

The schema is SYSTOOLS.

delete-older- A timestamp value that defines the starting point for deleting spooled files. Any
than spooled file older than this timestamp is eligible for deletion. The default is CURRENT
TIMESTAMP - 3 MONTHS.
p-output- A character or graphic string that specifies the name of a library. Any spooled file in any
queue-library- output queue in this library is eligible for deletion. The default is *ALL.
name
p-output- A character or graphic string that specifies an output queue name. Any spooled file in
queue-name this output queue is eligible for deletion. The default is *ALL.
p-user-name A character or graphic string that specifies the name of a user whose spooled files are
to be deleted. Any spooled file with this user name is eligible for deletion. The default
is *ALL.
preview A character or graphic string that indicates whether the identified spooled files should
be deleted or returned as a result set.
NO The spooled files will be deleted. This is the default.
YES A result set list of spooled files will be returned. No files will be deleted.

Note
This procedure is provided in the SYSTOOLS schema as an example of how to delete spooled files and
how to return a result set using an SQL procedure. Similar to other Db2 for i provided tools within
SYSTOOLS, the SQL source can be extracted and used as a model for building similar procedures, or to
create a customized version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example

Database performance and query optimization 935


• List all the spooled files in PRT01 that are older than 30 days.

CALL SYSTOOLS.DELETE_OLD_SPOOLED_FILES(DELETE_OLDER_THAN => CURRENT DATE - 30 DAYS,


P_OUTPUT_QUEUE_NAME => 'PRT01',
PREVIEW => 'YES');

• Delete all the spooled files in PRT01 that are older than 30 days.

CALL SYSTOOLS.DELETE_OLD_SPOOLED_FILES(DELETE_OLDER_THAN => CURRENT DATE - 30 DAYS,


P_OUTPUT_QUEUE_NAME => 'PRT01',
PREVIEW => 'NO');

GENERATE_PDF scalar function


The GENERATE_PDF scalar function generates a PDF file in the Integrated File System containing the
content of a spooled file.
This function requires the following product: 5770TS1 - Option 1 - Transform Services - AFP to PDF
Transform
Authorization: See Note below.

GENERATE_PDF ( job-name
JOB_NAME =>

, spooled-file-name
SPOOLED_FILE_NAME =>

, spooled-file-number
SPOOLED_FILE_NUMBER =>

, path-name )
PATH_NAME =>

The schema is SYSTOOLS.

job-name A character string containing a qualified job name. Can contain the following special
value:
* Use the name of the current job.

spooled-file-name A character string containing the name of the spooled file.


spooled-file- The number of the spooled file. Can contain the following special value:
number
*LAST The spooled file with the highest number with a name matching spooled-
file-name is selected.

path-name A character string containing the name of the path where the result PDF file is to be
written.
The result of the function is an integer. If the command is successful, the function returns a value of 1. If
the command returns an error, the function returns a value of -1.

Note
This function is provided in the SYSTOOLS schema as an example of how spooled file data can be
converted to PDF format by embedding the CPYSPLF CL command in an SQL scalar function. Similar to
other Db2 for i provided tools within SYSTOOLS, the SQL source can be extracted and used as a model for
building similar helper functions, or to create a customized version within a user-specified schema.

936 IBM i: Performance and Query Optimization


Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Convert the specified spooled file to PDF format and save it as /usr/listing1.

VALUES SYSTOOLS.GENERATE_PDF(
JOB_NAME => '908049/QUSER/QZDASOINIT',
SPOOLED_FILE_NAME => 'PGMA',
SPOOLED_FILE_NUMBER => 2,
PATH_NAME => '/usr/listing1');

OUTPUT_QUEUE_ENTRIES table function


The OUTPUT_QUEUE_ENTRIES table function returns one row for each spooled file in an output queue.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the output queue, and
– *READ authority to the output queue object, or
– *SPLCTL special authority, or
– *JOBCTL special authority and the output queue is defined with OPRCTL(*YES).

OUTPUT_QUEUE_ENTRIES ( outq-lib ,
OUTQ_LIB =>

outq-name
OUTQ_NAME =>

, detailed-info )
DETAILED_INFO =>

The schema is QSYS2.

outq-lib A character or graphic string expression that identifies the name of the library containing
outq-name. If this parameter is blank, the default of *LIBL is used.
outq-name A character or graphic string expression that identifies the name of an output queue.
detailed-info A character or graphic string expression that indicates the type of information to be
returned.

YES All the information available for the output queue is returned.
NO Only the general information is returned for the output queue. This is the
information in the columns prior to the ACCOUNTING_CODE column. This is the
default.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 237. OUTPUT_QUEUE_ENTRIES table function

Column Name Data Type Description

CREATE_TIMESTAMP TIMESTAMP The timestamp when the file was created.

SPOOLED_FILE_NAME VARCHAR(10) The file name that was specified by the user program when the file was created,
or the name of the device file used to create this file.

Database performance and query optimization 937


Table 237. OUTPUT_QUEUE_ENTRIES table function (continued)

Column Name Data Type Description

USER_NAME VARCHAR(10) The name of the user profile that produced the file.

USER_DATA VARCHAR(10) The user-specified data that describes this file. Contains null if there is no user-
specified data.

STATUS VARCHAR(15) Status of the spooled file.

CLOSED The file has been completely processed by a program


but SCHEDULE(*JOBEND) was specified and the job that
produced the file has not yet finished.

DEFERRED Printing of the file has been deferred.

DELETED The file has been deleted.

HELD The file has been held.

MESSAGE This file has a message which needs a reply or an action to


WAITING be taken.

OPEN The file has not been completely processed and is not ready
to be selected by a writer.

PENDING The file is pending to be printed.

PRINTING The file has been completely sent to the printer but print
complete status has not been sent back.

READY The file is available to be written.

SAVED The file has been printed and then saved. This file remains
saved until it is released.

SENDING The file is being sent or has been sent to a remote system.

WRITING This file is currently being produced by the writer.

SIZE INTEGER The size of the spooled file, in kilobytes.

TOTAL_PAGES INTEGER The total number of pages in the file.

COPIES SMALLINT The number of copies remaining to print.

FORM_TYPE VARCHAR(10) The type of form that should be loaded in the printer to print this file.

JOB_NAME VARCHAR(28) The qualified job name that produced the file.

DEVICE_TYPE VARCHAR(10) The type of data stream used to represent the file.

*AFPDS Advanced Function Presentation data stream

*AFPDSLINE AFPDS data mixed with 1403 line data

*IPDS Intelligent printer data stream

*LINE 1403 line data

*SCS Systems Network Architecture (SNA) character stream

*USERASCII ASCII data

OUTPUT_PRIORITY SMALLINT The priority of the spooled file.

FILE_NUMBER INTEGER The spooled file number of the specified file.

SYSTEM VARCHAR(8) The name of the system where the job that created the spooled file ran.

Values for the following columns are returned when the DETAILED_INFO parameter is YES. Otherwise, the columns will contain the null value.

ACCOUNTING_CODE VARCHAR(15) An identifier assigned by the system to record the resources used to write this
file.

EXPIRATION_DATE DATE The date the file will be eligible for removal from the system by the Delete
Expired Spooled Files (DLTEXPSPLF) command. Contains the null value if the file
will not expire.

SAVE_AFTER_WRITE VARCHAR(4) Indicates whether this file is to be saved after it is written.

*NO The file is deleted after it has been written.

*YES The file is set to save status after it has been written.

938 IBM i: Performance and Query Optimization


Table 237. OUTPUT_QUEUE_ENTRIES table function (continued)

Column Name Data Type Description

TOTAL_RECORDS INTEGER The total number of records in the printer file. It is possible for TOTAL_RECORDS
to be larger than MAXIMUM_RECORDS due to a reply to inquiry message
CPA4072.
Contains null if the spooled file data stream is not *AFPDS, *AFPDSLINE, or
*LINE, or if the file is open.

MAXIMUM_RECORDS INTEGER The maximum number of records allowed in the file at the time the file was
opened.
Contains null if there is no maximum.

PAGE_LENGTH INTEGER The page length, in lines per page, used by the spooled file.

LINES_PER_INCH DECIMAL(5,1) The number of lines per vertical inch defined in the printer file.

PAGE_WIDTH INTEGER The page width, in characters per printed line, used by the spooled file.

CHARACTERS_PER_INCH DECIMAL(5,1) The number of characters per horizontal inch, defined in the printer file.

PRINT_FIDELITY VARCHAR(8) The kind of error handling that is performed when printing.

*ABSOLUTE The file is printed only if it can be printed exactly as specified in


the data stream.

*CONTENT The printing overrides errors in the data stream and continues
printing with the printers best quality based on the content
fidelity.

PAGE_ROTATION VARCHAR(5) The degree of rotation of the text on the page, with respect to the way the form is
loaded into the printer.

*AUTO Computer output reduction is done automatically if the output is too


large to fit on the form, regardless of the print quality.

*DEVD The operating system sends a device default rotation value to the
printer. Page rotation is dependent on the printer's specifications.

*COR Output created for a form 13.2 inches wide by 11.0 inches long is
adjusted to print on a form 11.0 inches wide by 8.5 inches long.

PRINT_BOTH_SIDES VARCHAR(7) How the information prints.

*FORMDF The file uses a user-specified form definition. This value is used
only for *LINE, *AFPDS, and *AFPDSLINE printer device type files.

*NO The printing on the page is on one side only.

*YES The printing is on both sides of the page with the top of each page
the same for both sides.

*TUMBLE The printing is on both sides with the top of one printed page at the
opposite end from the top of the other printed page.

FILE_AVAILABLE VARCHAR(8) The time when this file becomes available to an output device for processing.

*IMMED The file is available as soon as the file is opened.

*FILEEND The file is available as soon as the file is closed.

*JOBEND The file is available when the job that owns the file is completed.

STARTING_PAGE VARCHAR(10) The page at which printing is to start for the file. Can contain the following special
value:

*ENDPAGE Printing starts with the last page.

ENDING_PAGE VARCHAR(10) The page at which printing is to end for the file. Can contain the following special
value:

*END Printing ends with the last page.

DEVICE_FILE_LIBRARY VARCHAR(10) The name of the library that contains the device file.

DEVICE_FILE_NAME VARCHAR(10) The name of the device file used to create the spooled file.

USER_DEFINED_DATA BINARY(255) Data defined by the user to be used by user applications or user-specified
programs that process spooled files.
Contains null when there is no user-defined data.

Database performance and query optimization 939


Table 237. OUTPUT_QUEUE_ENTRIES table function (continued)

Column Name Data Type Description

PROGRAM_THAT_OPENED_FILE_LIBRARY VARCHAR(10) The name of the library that contains the program that opened the file. Contains
null when the program is not known.

PROGRAM_THAT_OPENED_FILE_NAME VARCHAR(10) The name of the program that opened the spooled file. Contains null when the
program is not known.

FORM_DEFINITION_LIBRARY VARCHAR(10) The name of the library that contains the form definition. Contains null if
FORM_DEFINITION_NAME is a special value or if no form definition is specified
for this spooled file.

FORM_DEFINITION_NAME VARCHAR(10) The name of the form definition to use for this print request. Can contain one of
the following special values:

*DEVD The form definition in the printer device description will be used.

*INLINE The form definition defined in the spooled file data stream will be
used.

*INLINED The form definition defined in the spooled file data stream will be
used. If a form definition is not found, the form definition in the
printer device description will be used.

F1DFLT The form definition defined in the spooled file data stream will be
used.

Contains null when no form definition is specified for this spooled file.

PAGE_DEFINITION_LIBRARY VARCHAR(10) The name of the library containing the page definition. Contains the null value for
*LINE or *AFPDSLINE printer device type files.

PAGE_DEFINITION_NAME VARCHAR(10) The name of the page definition to use for the file. Contains the null value for
*LINE or *AFPDSLINE printer device type files.

FRONT_OVERLAY_LIBRARY VARCHAR(10) The name of the library containing the front overlay. Can contain one of these
special values:

*CURLIB The current ibrary is searched the front overlay.

*LIBL The library list is used to locate the front overlay.

Contains null when FRONT_OVERLAY_NAME is *NONE.

FRONT_OVERLAY_NAME VARCHAR(10) The name of the front overlay. Can contain the following special value:

*NONE The file does not use the front overlay.

BACK_OVERLAY_LIBRARY VARCHAR(10) The name of the library containing the back overlay. Contains null when
BACK_OVERLAY_NAME is a special value.

BACK_OVERLAY_NAME VARCHAR(10) The name of the back overlay. Can contain the following special values:

*FRONTOVL The back overlay is the same as the front overlay.

*NONE The file does not use the back overlay.

CHARACTER_SET_LIBRARY VARCHAR(10) The name of the library containing the font character set object. Can contain one
of these special values:

*CURLIB The current library is searched for the font character set object.

*LIBL The library list is used to locate the font character set object.

Contains null when CHARACTER_SET_NAME is *FONT.

CHARACTER_SET_NAME VARCHAR(10) The name of the font character set object used to print this file. Can contain the
following special value:

*FONT The information specified on the font parameter is used instead of the
character set and code page.

CODE_PAGE_LIBRARY VARCHAR(10) The name of the library containing the code page used to print this spooled file.
Can contain one of these special values:

*CURLIB The current library is searched for the code page name.

*LIBL The library list is used to locate the code page name.

Contains null when no code page is specified for this spooled file.

CODE_PAGE_NAME VARCHAR(10) The name of the code page used to print this spooled file. Contains null when no
code page is specified for this spooled file.

940 IBM i: Performance and Query Optimization


Table 237. OUTPUT_QUEUE_ENTRIES table function (continued)

Column Name Data Type Description

CHARACTER_SET_POINTSIZE DECIMAL(5,1) The point size in which this file's characters should be printed. Contains null if the
character set does not have a point size.

CODED_FONT_LIBRARY VARCHAR(10) The name of the library containing the coded font used to print this spooled file.
Can contain one of these special values:

*CURLIB The current library is searched for the coded font.

*LIBL The library list is used to locate the coded font.

Contains null when CODED_FONT_NAME is *FNTCHRSET.

CODED_FONT_NAME VARCHAR(10) The name of the coded font used to print this spooled file. Can contain the
following special value:

*FNTCHRSET The values used are the values specified on the character set
name and library name and code page name and library name
fields.

CODED_FONT_POINTSIZE DECIMAL(5,1) The point size in which this file's characters should be printed. Contains null if the
coded font does not have a point size.

MULTIBYTE_DATA VARCHAR(10) Whether the file can contain double-byte character set (DBCS) data, Unicode
data, or both. Values are *YES and *NO.

DBCS_CODED_FONT_LIBRARY VARCHAR(10) The name of the library containing the DBCS-coded font. Can contain one of these
special values:

*CURLIB The current library is searched for the DBCS-coded font.

*LIBL The library list is used to locate the DBCS-coded font.

Contains null when DBCS_CODED_FONT_NAME is *SYSVAL.

DBCS_CODED_FONT_NAME VARCHAR(10) The name of the DBCS-coded font used to print DBCS-coded data on printers
configured as AFP(*YES). Can contain the following special value:

*SYSVAL The DBCS-coded font specified in the system value is used.

DBCS_CODED_FONT_POINTSIZE DECIMAL(5,1) The point size in which this file's DCBS characters should be printed. Contains
null if the DBCS-coded font does not have a point size.

Example

Find the 100 largest spool files in the QEZJOBLOG output queue. Since no detailed information is needed,
specify NO to avoid the additional processing.

SELECT *
FROM TABLE(QSYS2.OUTPUT_QUEUE_ENTRIES('*LIBL', 'QEZJOBLOG', 'NO')) A
ORDER BY SIZE DESC
FETCH FIRST 100 ROWS ONLY

OUTPUT_QUEUE_ENTRIES view
The OUTPUT_QUEUE_ENTRIES view returns one row for each spooled file in every output queue. This
view uses the QSYS2.OUTPUT_QUEUE_ENTRIES table function with DETAILED_INFO => 'YES'.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the output queue, and
– *READ authority to the output queue object, or
– *SPLCTL special authority, or
– *JOBCTL special authority and the output queue is defined with OPRCTL(*YES).
To achieve the best performance when querying the OUTPUT_QUEUE_ENTRIES view, the use
of a WHERE clause is recommended if you are interested in examining specific output
queue libraries or output queues. OUTPUT_QUEUE_ENTRIES_BASIC typically performs much

Database performance and query optimization 941


better than OUTPUT_QUEUE_ENTRIES. OUTPUT_QUEUE_ENTRIES should only be used when
OUTPUT_QUEUE_ENTRIES_BASIC does not include the columns needed by the query.
The following table describes the columns in the view. The system name is OUTQ_INFO. The schema is
QSYS2.
Table 238. OUTPUT_QUEUE_ENTRIES view

Column Name System Column Name Data Type Description

OUTPUT_QUEUE_NAME OUTQ VARCHAR(10) Name of the output queue containing the spooled file.

OUTPUT_QUEUE_LIBRARY_NAME OUTQLIB VARCHAR(10) The name of the library that contains the output queue.

CREATE_TIMESTAMP CREATED TIMESTAMP The timestamp when the file was created.

SPOOLED_FILE_NAME SPOOLNAME VARCHAR(10) The file name that was specified by the user program when the
file was created, or the name of the device file used to create
this file.

USER_NAME USER_NAME VARCHAR(10) The name of the user profile that produced the file.

USER_DATA USER_DATA VARCHAR(10) The user-specified data that describes this file. Contains null if
there is no user-specified data.
Nullable

STATUS STATUS VARCHAR(15) Status of the spooled file.

CLOSED The file has been completely processed by


a program but SCHEDULE(*JOBEND) was
specified and the job that produced the file
has not yet finished.

DEFERRED Printing of the file has been deferred.

DELETED The file has been deleted.

HELD The file has been held.

MESSAGE This file has a message which needs a reply or


WAITING an action to be taken.

OPEN The file has not been completely processed


and is not ready to be selected by a writer.

PENDING The file is pending to be printed.

PRINTING The file has been completely sent to the


printer but print complete status has not been
sent back.

READY The file is available to be written.

SAVED The file has been printed and then saved. This
file remains saved until it is released.

SENDING The file is being sent or has been sent to a


remote system.

WRITING This file is currently being produced by the


writer.

SIZE SIZE INTEGER The size of the spooled file, in kilobytes.

TOTAL_PAGES PAGES INTEGER The total number of pages in the file.

COPIES COPIES SMALLINT The number of copies remaining to print.

FORM_TYPE FORM_TYPE VARCHAR(10) The type of form that should be loaded in the printer to print this
file.

JOB_NAME JOB_NAME VARCHAR(28) The qualified job name that produced the file.

942 IBM i: Performance and Query Optimization


Table 238. OUTPUT_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data Type Description

DEVICE_TYPE DEVTYPE VARCHAR(10) The type of data stream used to represent the file.

*AFPDS Advanced Function Presentation data stream

*AFPDSLINE AFPDS data mixed with 1403 line data

*IPDS Intelligent printer data stream

*LINE 1403 line data

*SCS Systems Network Architecture (SNA) character


stream

*USERASCII ASCII data

OUTPUT_PRIORITY OUTPTY SMALLINT The priority of the spooled file.

FILE_NUMBER FILENUM INTEGER The spooled file number of the specified file.

SYSTEM SYSTEM VARCHAR(8) The name of the system where the job that created the spooled
file ran.

ACCOUNTING_CODE ACGCDE VARCHAR(15) An identifier assigned by the system to record the resources
used to write this file.

EXPIRATION_DATE EXPDATE DATE The date the file will be eligible for removal from the system
by the Delete Expired Spooled Files (DLTEXPSPLF) command.
Nullable Contains the null value if the file will not expire.

SAVE_AFTER_WRITE SAVEAFTER VARCHAR(4) Indicates whether this file is to be saved after it is written.

*NO The file is deleted after it has been written.

*YES The file is set to save status after it has been written.

TOTAL_RECORDS TOTALRCDS INTEGER The total number of records in the printer file. It is possible for
TOTAL_RECORDS to be larger than MAXIMUM_RECORDS due to
a reply to inquiry message CPA4072.
Contains null if the spooled file data stream is not *AFPDS,
*AFPDSLINE, or *LINE, or if the file is open.

MAXIMUM_RECORDS MAXRCDS INTEGER The maximum number of records allowed in the file at the time
the file was opened.
Contains null if there is no maximum.

PAGE_LENGTH PAGELEN INTEGER The page length, in lines per page, used by the spooled file.

LINES_PER_INCH LPI DECIMAL(5,1) The number of lines per vertical inch defined in the printer file.

PAGE_WIDTH WIDTH INTEGER The page width, in characters per printed line, used by the
spooled file.

CHARACTERS_PER_INCH CPI DECIMAL(5,1) The number of characters per horizontal inch, defined in the
printer file.

PRINT_FIDELITY FIDELITY VARCHAR(8) The kind of error handling that is performed when printing.

*ABSOLUTE The file is printed only if it can be printed exactly


as specified in the data stream.

*CONTENT The printing overrides errors in the data stream


and continues printing with the printers best
quality based on the content fidelity.

PAGE_ROTATION ROTATION VARCHAR(5) The degree of rotation of the text on the page, with respect to
the way the form is loaded into the printer.

*AUTO Computer output reduction is done automatically if


the output is too large to fit on the form, regardless of
the print quality.

*DEVD The operating system sends a device default rotation


value to the printer. Page rotation is dependent on
the printer's specifications.

*COR Output created for a form 13.2 inches wide by 11.0


inches long is adjusted to print on a form 11.0 inches
wide by 8.5 inches long.

Database performance and query optimization 943


Table 238. OUTPUT_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data Type Description

PRINT_BOTH_SIDES BOTHSIDES VARCHAR(7) How the information prints.

*FORMDF The file uses a user-specified form definition.


This value is used only for *LINE, *AFPDS, and
*AFPDSLINE printer device type files.

*NO The printing on the page is on one side only.

*YES The printing is on both sides of the page with the


top of each page the same for both sides.

*TUMBLE The printing is on both sides with the top of one


printed page at the opposite end from the top of
the other printed page.

FILE_AVAILABLE FILEAVAIL VARCHAR(8) The time when this file becomes available to an output device
for processing.

*IMMED The file is available as soon as the file is opened.

*FILEEND The file is available as soon as the file is closed.

*JOBEND The file is available when the job that owns the
file is completed.

STARTING_PAGE STARTPAGE VARCHAR(10) The page at which printing is to start for the file. Can contain the
following special value:

*ENDPAGE Printing starts with the last page.

ENDING_PAGE ENDPAGE VARCHAR(10) The page at which printing is to end for the file. Can contain the
following special value:

*END Printing ends with the last page.

DEVICE_FILE_LIBRARY DEVLIB VARCHAR(10) The name of the library that contains the device file.

DEVICE_FILE_NAME DEVFILE VARCHAR(10) The name of the device file used to create the spooled file.

USER_DEFINED_DATA USRDFNDTA BINARY(255) Data defined by the user to be used by user applications or
user-specified programs that process spooled files.
Contains null when there is no user-defined data.

PROGRAM_THAT_OPENED_ LIBOPEN VARCHAR(10) The name of the library that contains the program that opened
FILE_LIBRARY the file. Contains null when the program is not known.
Nullable

PROGRAM_THAT_OPENED_ PGMOPEN VARCHAR(10) The name of the program that opened the spooled file. Contains
FILE_NAME null when the program is not known.
Nullable

FORM_DEFINITION_LIBRARY FORMLIB VARCHAR(10) The name of the library that contains the form definition.
Contains null if FORM_DEFINITION_NAME is a special value or if
Nullable no form definition is specified for this spooled file.

FORM_DEFINITION_NAME FORMNAME VARCHAR(10) The name of the form definition to use for this print request. Can
contain one of the following special values:
Nullable
*DEVD The form definition in the printer device
description will be used.

*INLINE The form definition defined in the spooled file


data stream will be used.

*INLINED The form definition defined in the spooled file


data stream will be used. If a form definition is
not found, the form definition in the printer device
description will be used.

F1DFLT The form definition defined in the spooled file


data stream will be used.

Contains null when no form definition is specified for this


spooled file.

PAGE_DEFINITION_LIBRARY PAGELIB VARCHAR(10) The name of the library containing the page definition. Contains
the null value for *LINE or *AFPDSLINE printer device type files.
Nullable

944 IBM i: Performance and Query Optimization


Table 238. OUTPUT_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data Type Description

PAGE_DEFINITION_NAME PAGENAME VARCHAR(10) The name of the page definition to use for the file. Contains the
null value for *LINE or *AFPDSLINE printer device type files.
Nullable

FRONT_OVERLAY_LIBRARY FRONTLIB VARCHAR(10) The name of the library containing the front overlay. Can contain
one of these special values:
Nullable
*CURLIB The current ibrary is searched the front overlay.

*LIBL The library list is used to locate the front overlay.

Contains null when FRONT_OVERLAY_NAME is *NONE.

FRONT_OVERLAY_NAME FRONTNAME VARCHAR(10) The name of the front overlay. Can contain the following special
value:

*NONE The file does not use the front overlay.

BACK_OVERLAY_LIBRARY BACKLIB VARCHAR(10) The name of the library containing the back overlay. Contains
null when BACK_OVERLAY_NAME is a special value.
Nullable

BACK_OVERLAY_NAME BACKNAME VARCHAR(10) The name of the back overlay. Can contain the following special
values:

*FRONTOVL The back overlay is the same as the front


overlay.

*NONE The file does not use the front overlay.

CHARACTER_SET_LIBRARY CHRSETLIB VARCHAR(10) The name of the library containing the font character set object.
Can contain one of these special values:
Nullable
*CURLIB The current library is searched for the font
character set object.

*LIBL The library list is used to locate the font character


set object.

Contains null when CHARACTER_SET_NAME is *FONT.

CHARACTER_SET_NAME CHRSETNAME VARCHAR(10) The name of the font character set object used to print this file.
Can contain the following special value:

*FONT The information specified on the font parameter is


used instead of the character set and code page.

CODE_PAGE_LIBRARY CODELIB VARCHAR(10) The name of the library containing the code page used to print
this spooled file. Can contain one of these special values:
Nullable
*CURLIB The current library is searched for the code page
name.

*LIBL The library list is used to locate the code page


name.

Contains null when no code page is specified for this spooled


file.

CODE_PAGE_NAME CODENAME VARCHAR(10) The name of the code page used to print this spooled file.
Contains null when no code page is specified for this spooled
Nullable file.

CHARACTER_SET_POINTSIZE CHARSIZE DECIMAL(5,1) The point size in which this file's characters (defined by
CHARACTER_SET) should be printed. Contains null if the
Nullable character set does not have a point size.

CODED_FONT_LIBRARY FONTLIB VARCHAR(10) The name of the library containing the coded font used to print
this spooled file. Can contain one of these special values:
Nullable
*CURLIB The current library is searched for the coded font.

*LIBL The library list is used to locate the coded font.

Contains null when CODED_FONT_NAME is *FNTCHRSET.

Database performance and query optimization 945


Table 238. OUTPUT_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data Type Description

CODED_FONT_NAME FONTNAME VARCHAR(10) The name of the coded font used to print this spooled file. Can
contain the following special value:

*FNTCHRSET The values used are the values specified on


the character set name and library name and
code page name and library name fields.

CODED_FONT_POINTSIZE FONTSIZE DECIMAL(5,1) The point size in which this file's characters (defined by
CODED_FONT) should be printed. Contains null if the coded font
Nullable does not have a point size.

MULTIBYTE_DATA MULTIBYTE VARCHAR(10) Whether the file can contain double-byte character set (DBCS)
data, Unicode data, or both. Values are *YES and *NO.

DBCS_CODED_FONT_LIBRARY DBCSLIB VARCHAR(10) The name of the library containing the DBCS-coded font. Can
contain one of these special values:
Nullable
*CURLIB The current library is searched for the DBCS-coded
font.

*LIBL The library list is used to locate the DBCS-coded


font.

Contains null when DBCS_CODED_FONT_NAME is *SYSVAL.

DBCS_CODED_FONT_NAME DBCSNAME VARCHAR(10) The name of the DBCS-coded font used to print DBCS-coded
data on printers configured as AFP(*YES). Can contain the
following special value:

*SYSVAL The DBCS-coded font specified in the system value


is used.

DBCS_CODED_FONT_POINTSIZE DBCSSIZE DECIMAL(5,1) The point size in which this file's DCBS characters (defined
by DBCS_CODED_FONT) should be printed. Contains null if the
Nullable DBCS-coded font does not have a point size.

Example

For the output queue with the largest number of files, determine how many kilobytes of data would be
deleted by running the Delete Expired Spooled Files (DLTEXPSPLF) CL command.

WITH MOSTFILES(OUTQ_LIB, OUTQ_NAME) AS (


SELECT OUTPUT_QUEUE_LIBRARY_NAME, OUTPUT_QUEUE_NAME
FROM QSYS2.OUTPUT_QUEUE_INFO
ORDER BY NUMBER_OF_FILES DESC
LIMIT 1
)
SELECT SUM(SIZE) AS KB_TO_CLEAR
FROM MOSTFILES, QSYS2.OUTPUT_QUEUE_ENTRIES
WHERE OUTPUT_QUEUE_LIBRARY_NAME = OUTQ_LIB AND
OUTPUT_QUEUE_NAME = OUTQ_NAME AND
EXPIRATION_DATE IS NOT NULL AND
EXPIRATION_DATE < CURRENT DATE;

OUTPUT_QUEUE_ENTRIES_BASIC view
The OUTPUT_QUEUE_ENTRIES_BASIC view returns one row for each spooled file in every output queue.
This view uses the QSYS2.OUTPUT_QUEUE_ENTRIES table function with DETAILED_INFO => 'NO'.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the output queue, and
– *READ authority to the output queue object, or
– *SPLCTL special authority, or
– *JOBCTL special authority and the output queue is defined with OPRCTL(*YES).
To achieve the best performance when querying the OUTPUT_QUEUE_ENTRIES_BASIC view,
the use of a WHERE clause is recommended if you are interested in examining specific

946 IBM i: Performance and Query Optimization


output queue libraries or output queues. OUTPUT_QUEUE_ENTRIES_BASIC typically performs
much better than OUTPUT_QUEUE_ENTRIES. OUTPUT_QUEUE_ENTRIES should only be used when
OUTPUT_QUEUE_ENTRIES_BASIC does not include the columns needed by the query.
The following table describes the columns in the view. The system name is OUTQ_INFOB. The schema is
QSYS2.
Table 239. OUTPUT_QUEUE_ENTRIES_BASIC view

Column Name System Column Name Data Type Description

OUTPUT_QUEUE_NAME OUTQ VARCHAR(10) Name of the output queue containing the spooled file.

OUTPUT_QUEUE_LIBRARY_NAME OUTQLIB VARCHAR(10) The name of the library that contains the output queue.

CREATE_TIMESTAMP CREATED TIMESTAMP The timestamp when the file was created.

SPOOLED_FILE_NAME SPOOLNAME VARCHAR(10) The file name that was specified by the user program when the
file was created, or the name of the device file used to create
this file.

USER_NAME USER_NAME VARCHAR(10) The name of the user profile that produced the file.

USER_DATA USER_DATA VARCHAR(10) The user-specified data that describes this file. Contains null if
there is no user-specified data.
Nullable

STATUS STATUS VARCHAR(15) Status of the spooled file.

CLOSED The file has been completely processed by


a program but SCHEDULE(*JOBEND) was
specified and the job that produced the file
has not yet finished.

DEFERRED Printing of the file has been deferred.

DELETED The file has been deleted.

HELD The file has been held.

MESSAGE This file has a message which needs a reply or


WAITING an action to be taken.

OPEN The file has not been completely processed


and is not ready to be selected by a writer.

PENDING The file is pending to be printed.

PRINTING The file has been completely sent to the


printer but print complete status has not been
sent back.

READY The file is available to be written.

SAVED The file has been printed and then saved. This
file remains saved until it is released.

SENDING The file is being sent or has been sent to a


remote system.

WRITING This file is currently being produced by the


writer.

SIZE SIZE INTEGER The size of the spooled file, in kilobytes.

TOTAL_PAGES PAGES INTEGER The total number of pages in the file.

COPIES COPIES SMALLINT The number of copies remaining to print.

FORM_TYPE FORM_TYPE VARCHAR(10) The type of form that should be loaded in the printer to print this
file.

JOB_NAME JOB_NAME VARCHAR(28) The qualified job name that produced the file.

Database performance and query optimization 947


Table 239. OUTPUT_QUEUE_ENTRIES_BASIC view (continued)

Column Name System Column Name Data Type Description

DEVICE_TYPE DEVTYPE VARCHAR(10) The type of data stream used to represent the file.

*AFPDS Advanced Function Presentation data stream

*AFPDSLINE AFPDS data mixed with 1403 line data

*IPDS Intelligent printer data stream

*LINE 1403 line data

*SCS Systems Network Architecture (SNA) character


stream

*USERASCII ASCII data

OUTPUT_PRIORITY OUTPTY SMALLINT The priority of the spooled file.

FILE_NUMBER FILENUM INTEGER The spooled file number of the specified file.

SYSTEM SYSTEM VARCHAR(8) The name of the system where the job that created the spooled
file ran.

Examples
• Find the 100 largest spool files in the QEZJOBLOG output queue.

SELECT * FROM QSYS2.OUTPUT_QUEUE_ENTRIES_BASIC


WHERE OUTPUT_QUEUE_NAME = 'QEZJOBLOG'
ORDER BY SIZE DESC
FETCH FIRST 100 ROWS ONLY

• Find the top 10 consumers of SPOOL storage.

SELECT USER_NAME, SUM(SIZE) AS TOTAL_SPOOL_SPACE


FROM QSYS2.OUTPUT_QUEUE_ENTRIES_BASIC
WHERE USER_NAME NOT LIKE 'Q%'
GROUP BY USER_NAME
ORDER BY TOTAL_SPOOL_SPACE DESC LIMIT 10;

OUTPUT_QUEUE_INFO view
The OUTPUT_QUEUE_INFO view returns one row for each output queue.
The values returned for the columns in the view are similar to the values returned by the Retrieve Output
Queue Information (QSPROUTQ) API. Refer to the API for more detailed information.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the output queue, and
– *READ authority to the output queue object, or
– *SPLCTL special authority, or
– *JOBCTL special authority and the output queue is defined with OPRCTL(*YES).
The following table describes the columns in the view. The system name is OUTQ_DTL. The schema is
QSYS2.
Table 240. OUTPUT_QUEUE_INFO view

Column Name System Column Name Data Type Description

OUTPUT_QUEUE_NAME OUTQ VARCHAR(10) Name of the output queue.

OUTPUT_QUEUE_LIBRARY_NAME OUTQLIB VARCHAR(10) The name of the library that contains the output queue.

NUMBER_OF_FILES FILES INTEGER The total number of spooled files currently on this output queue.

NUMBER_OF_WRITERS WRITERS INTEGER The number of printer writers that have been started to this
output queue.

WRITERS_TO_AUTOSTART AUTOSTART INTEGER The number of remote printer writers to autostart to this output
queue at system IPL.

948 IBM i: Performance and Query Optimization


Table 240. OUTPUT_QUEUE_INFO view (continued)

Column Name System Column Name Data Type Description

PRINTER_DEVICE_NAME DEV_NAME VARCHAR(10) The name of the printer device. If more than one writer is started,
this is the printer device name of the first writer.
Nullable
Contains the null value if WRITER_TYPE is not PRINTER.

ORDER_OF_FILES FILE_ORDER VARCHAR(7) The order of the spooled files on the output queue.

*FIFO The queue is first-in first-out for each file. That is,
on the queue, new spooled files are placed behind
all other spooled files that have the same priority.

*JOBNBR The queue entries for the spooled files are sorted
in priority sequence using the job number (the date
and time that the job entered the system) of the job
that created the spooled file.

DISPLAY_ANY_FILE ANYFILE VARCHAR(6) Whether users who have authority to read this output queue can
display the output data of any output file on this queue, or only
the data in their own files.

*NO Users authorized to the queue can only display,


copy, or send their own spooled files, unless one
of the following applies:
• they have *SPLCTL special authority, or
• they have *JOBCTL special authority and
OPERATOR_CONTROLLED is *YES.

*OWNER Only the owner of a file or a user with *SPLCTL


authority can display, copy, send, or move their own
spooled files to another output queue.

*YES Any user having authority to read the queue can


display, copy, or send the data of any file on the
queue.

JOB_SEPARATORS JOB_SEP VARCHAR(4) The number of job separators (0-9) to be placed at the beginning
of the output for each job having spooled file entries on this
output queue. Can also contain the following special value:

*MSG No job separators are used; instead a message is sent


to the writer's message queue at the end of each job
indicating that the output can be removed.

MAXIMUM_PAGES MAX_PAGES INTEGER Only spooled files with this number of pages or less
will print between MAXIMUM_PAGES_STARTING_TIME and
Nullable MAXIMUM_PAGES_ENDING_TIME. If more than one set of
maximum spooled file size values is defined for this output
queue, only information for the first set is returned.
Contains the null value if no maximum spooled file size is defined.

MAXIMUM_PAGES_STARTING_ MAX_START TIME The starting time, in local job time, that spooled files exceeding
TIME MAXIMUM_PAGES will be restricted from printing. If a spooled
Nullable file exceeds the page limit it will be in deferred status until
ENDING_TIME.
Contains the null value if no maximum spooled file size is defined.

MAXIMUM_PAGES_ENDING_ MAX_END TIME The ending time, in local job time, when spooled files exceeding
TIME MAXIMUM_PAGES will be allowed to print.
Nullable
Contains the null value if no maximum spooled file size is defined.

OPERATOR_CONTROLLED OPR_CTRL VARCHAR(4) Whether users with job control authority are allowed to manage
or control the files on this queue. Users have job control authority
if SPCAUT(*JOBCTL) is specified in their user profile.

*NO This queue and its entries cannot be controlled or


changed by users with job control authority unless they
also have some other special authority.

*YES Users with job control authority can control the queue
and make changes to the files on the queue.

Database performance and query optimization 949


Table 240. OUTPUT_QUEUE_INFO view (continued)

Column Name System Column Name Data Type Description

AUTHORITY_TO_CHECK ALL_AUTH VARCHAR(7) Indicates what type of authorities to the output queue allow the
user to control all the files on the queue.

*DTAAUT Any user with *READ, *ADD, and *DELETE authority


to the output queue can control all output files on
the queue.

*OWNER Only the owner of the output queue can control all
the output files on the queue.

DATA_QUEUE_LIBRARY DTAQ_LIB VARCHAR(10) The name of the library containing the data queue.

Nullable Contains the null value if no data queue is associated with this
output queue.

DATA_QUEUE_NAME DTAQ_NAME VARCHAR(10) The name of the data queue associated with this output queue.

Nullable Contains the null value if no data queue is associated with this
output queue.

OUTPUT_QUEUE_STATUS STATUS VARCHAR(8) The status of the output queue.

HELD The queue is held.

RELEASED The queue is released.

WRITER_JOB_NAME WRITER_JOB VARCHAR(28) The qualified job name of the writer job. If more than one writer is
started, this is the name of the first writer.
Nullable
Contains the null value if a writer job is not started for this queue.

WRITER_JOB_STATUS WRITER_STS VARCHAR(4) The status of the writer job. If more than one writer is started,
this is the status of the first writer.
Nullable
END The writer job has ended.

HLD The writer job is held.

JOBQ The writer job is on the job queue.

MSGW The writer job is waiting for a message response.

STR The writer job is started for the output queue.

Contains the null value if a writer job is not started for this queue.

WRITER_TYPE WRITER_TYP VARCHAR(7) The type of writer started for this output queue.

Nullable PRINTER Printer writer.

REMOTE Remote writer.

Contains the null value if a writer job is not started for this queue.

SPOOLED_FILE_ASP_ATTRIBUTE ASP_ATTR VARCHAR(8) The auxiliary storage pool (ASP) where the spooled files are to
reside.

*OUTQASP The spooled files reside in the auxiliary storage


pool in which the output queue resides.

*SYSTEM The spooled files reside in the system auxiliary


storage pool.

SPOOLED_FILE_ASP_NUMBER ASPNUM INTEGER The number of the auxiliary storage pool (ASP) where the spooled
files reside.

SPOOLED_FILE_ASPGRP ASPGRP VARCHAR(10) The name of the auxiliary storage pool (ASP) device where the
spooled files reside. Can also contain the following special value:
Nullable
*SYSBAS The spooled files resides in the system ASP (ASP 1)
or one of the defined basic user ASPs (ASPs 2-32).

Contains the null value if the name is not available.

TEXT_DESCRIPTION TEXT VARCHAR(50) The text description of the output queue.

Nullable Contains the null value if the output queue has no description.

950 IBM i: Performance and Query Optimization


Table 240. OUTPUT_QUEUE_INFO view (continued)

Column Name System Column Name Data Type Description

MESSAGE_QUEUE_LIBRARY MSGQ_LIB VARCHAR(10) The name of the library containing the message queue. Can
contain the following special value:
Nullable
*LIBL The library list is searched to find the message queue.

Contains the null value if the output queue is not a remote output
queue or if WRITER_TYPE is PRINTER.

MESSAGE_QUEUE_NAME MSGQ_NAME VARCHAR(10) The name of the message queue to which messages, created by
the remote writer started to this output queue, are sent.
Nullable
Contains the null value if the output queue is not a remote output
queue or if WRITER_TYPE is PRINTER.

HOST_PRINT_TRANSFORM TRANSFORM VARCHAR(4) Whether to use the host print transform function to transform a
spooled file.
Nullable
*NO Do not transform data streams using host print
transform.

*YES Transform data streams using host print transform.

Contains the null value if NETWORK_CONNECTION_TYPE is *SNA


and USER_DRIVER_PROGRAM_NAME is null.

IMAGE_CONFIGURATION_NAME IMAGE_NAME VARCHAR(10) The name of the image configuration.

Nullable Contains the null value if no image configuration is used when


transforming the spooled file before sending.

MANUFACTURER_TYPE_AND_ TYPE_MODEL VARCHAR(17) The manufacturer, type, and model for a printer using the host
MODEL print transform function.
Nullable
See Printer Model Settings for Host Print Transform (HPT) in the
IBM Support Portal for the list of supported values.
Contains the null value when NETWORK_CONNECTION_TYPE
is *SNA, or when NETWORK_CONNECTION_TYPE is *IP and
HOST_PRINT_TRANSFORM is *NO.

WORKSTATION_CUSTOMIZING_ CUSTOM_LIB VARCHAR(10) The library name for the workstation customizing object.
OBJECT_LIBRARY Nullable Contains the null value if there is no workstation customizing
object or if NETWORK_CONNECTION_TYPE is *SNA and
USER_DRIVER_PROGRAM_NAME is null.

WORKSTATION_CUSTOMIZING_ CUSTOM_NAM VARCHAR(10) The name of an object that consists of a table of attributes used
OBJECT_NAME to customize a given ASCII device.
Nullable
Contains the null value if there is no workstation customizing
object or if NETWORK_CONNECTION_TYPE is *SNA and
USER_DRIVER_PROGRAM_NAME is null.

NETWORK_CONNECTION_TYPE NET_TYPE VARCHAR(7) The type of network connection to the remote system.
Nullable *IP The TCP/IP network is used as the connectivity to
the remote system.

*SNA The SNADS network is used as the connectivity to


the remote system.

*USRDFN A user-defined connectivity is used as the


connectivity to the remote system.

Contains the null value if the output queue is not a remote output
queue.

Database performance and query optimization 951


Table 240. OUTPUT_QUEUE_INFO view (continued)

Column Name System Column Name Data Type Description

DESTINATION_TYPE DEST_TYPE VARCHAR(8) The type of destination system that spooled files on this output
queue are being sent to.
Nullable
*NDS The destination is Novell NetWare 3 or 4, and the
connection type is *USRDFN.

*OS400 The destination system is an IBM i.

*OTHER The destination system does not match any of the


other special values. This is commonly used when
the destination is a printer.

*PSF2 The destination system is a PC using Print Services


Facility/2.

*S390 This destination system is a System/390®® system.

Contains the null value if the output queue is not a remote output
queue.

REMOTE_SYSTEM_NAME REMOTE_NAM VARCHAR(255) The name of the remote system.

Nullable Contains the null value if the output queue is not a remote output
queue.

REMOTE_PRINTER_QUEUE REMOTE_PRT VARCHAR(255) The name of the remote printer. Can also contain one of these
special values:
Nullable
*SYSTEM The default system printer on the remote system
will determine the printer queue.

*USER The user profile that creates the spooled file will
determine the user ID on the remote system that it
is sent to.

Contains the null value if the output queue is not a remote output
queue.

INTERNET_ADDRESS IP_ADDRESS VARCHAR(15) The internet address of the remote system to which the print
request will be sent.
Nullable
Contains the null value if the output queue is not a remote output
queue.

DESTINATION_OPTIONS DEST_OPT VARCHAR(128) Destination-dependent options that are specific to a particular


implementation of an LPR Print Server. Can also contain the
Nullable special values:

*NOWAIT The remote writer will not wait for confirmation


that the destination system has finished
processing the spooled file.

*USRDFNTXT Use the value for the user-defined text of the


user profile when the spooled file was created.

Contains the null value if the output queue is not a remote output
queue.

USER_DRIVER_PROGRAM_ UDP_LIB VARCHAR(10) The name of the library that contains the user driver program.
LIBRARY Can also be one of these special values:
Nullable
*CURLIB The current library for the job is used to locate the
user driver program.

*LIBL The library list used to locate the user driver


program.

Contains the null value if no user driver program is specified.

USER_DRIVER_PROGRAM_NAME UDP_NAME VARCHAR(10) The name of the user-specified driver program that is used to
process the spooled files on the output queue.
Nullable
Contains the null value if no user driver program is specified.

952 IBM i: Performance and Query Optimization


Table 240. OUTPUT_QUEUE_INFO view (continued)

Column Name System Column Name Data Type Description

USER_DEFINED_OBJECT_LIBRARY UDO_LIB VARCHAR(10) The name of the library that contains the user-defined object.
Can also be one of these special values:
Nullable
*CURLIB The current library for the job is used to locate the
user-defined object.

*LIBL The library list used to locate the user-defined


object.

Contains the null value if no user-defined object is specified.

USER_DEFINED_OBJECT_NAME UDO_NAME VARCHAR(10) The name of the user-defined object that is used by user
applications or user-specified programs that process spooled
Nullable files.
Contains the null value if no user-defined object is specified.

USER_DEFINED_OBJECT_TYPE UDO_TYPE VARCHAR(7) The type of the user-defined object.

Nullable *DTAARA Data area.

*DTAQ Data queue.

*FILE File.

*PSFCFG PSF configuration object.

*USRIDX User index.

*USRQ User queue.

*USRSPC User space.

Contains the null value if no user-defined object is specified.

DATA_TRANSFORM_PROGRAM_ DTP_LIB VARCHAR(10) The name of the library that contains the data transform program.
LIBRARY Can also be one of these special values:
Nullable
*CURLIB The current library for the job is used to locate the
data transform program.

*LIBL The library list used to locate the data transform


program.

Contains the null value if no data transform program is specified.

DATA_TRANSFORM_PROGRAM_ DTP_NAME VARCHAR(10) The name of the user-specified data transform program that is
NAME used by the driver program.
Nullable
Contains the null value if no data transform program is specified.

USER_DEFINED_OPTION_1 UDEF_OPT1 VARCHAR(10) The first user-defined option.

Nullable Contains the null value if there are no user-defined options.

USER_DEFINED_OPTION_2 UDEF_OPT2 VARCHAR(10) The second user-defined option.

Nullable Contains the null value if there are not at least two user-defined
options.

USER_DEFINED_OPTION_3 UDEF_OPT3 VARCHAR(10) The third user-defined option.

Nullable Contains the null value if there are not at least three user-defined
options.

USER_DEFINED_OPTION_4 UDEF_OPT4 VARCHAR(10) The fourth user-defined option.

Nullable Contains the null value if there are not at least four user-defined
options.

USER_DEFINED_DATA UDEF_DATA VARBINARY(5000) Data defined by the user to be used by user applications or user-
specified programs that process spooled files.
Nullable
Contains the null value if there is no user-defined data.

LDAP_PUBLISHING_STATUS PUBLISHED VARCHAR(3) Whether the output queue is published in the network directory.

NO Output queue is not published.

YES Output queue is published.

Database performance and query optimization 953


Table 240. OUTPUT_QUEUE_INFO view (continued)

Column Name System Column Name Data Type Description

FORMS_CONTROL_BUFFER FORMS_BUF VARCHAR(8) The forms control buffer (FCB) for files sent to a VM/MVS™ host
system. Contains either the name of the FCB or one of the
Nullable following special values:

*PRTF The first 8 characters of the printer file used to


spool the file determines the name of the FCB.

*USRDTA The first 8 characters of the user data (USRDATA)


spooled file attribute determines the name of the
FCB. If the user data is blank, no FCB is used.

Contains the null value if no FCB is used when sending


spooled files or if NETWORK_CONNECTION_TYPE is not *SNA or
DESTINATION_TYPE is not *S390.

VM_MVS_CLASS VM_CLASS CHAR(1) The VM/MVS SYSOUT class for distributions sent to a VM host
system or to a MVS host system. Values are A-Z, 0-9 to indicate
Nullable the distribution class.
Contains the null value if not defined for this output queue.

Example

SELECT * FROM QSYS2.OUTPUT_QUEUE_INFO

PRINTER_FILE_INFO view
The PRINTER_FILE_INFO view returns many attributes of IBM i printer files.
The information is returned by using the Display File Description (DSPFD) CL command.
Authorization: See Note below.
The following table describes the columns in the view. The system name is PRTF_INFO. The schema is
SYSTOOLS.
Table 241. PRINTER_FILE_INFO view

Column name System column Data type Description


name

PRINTER_FILE_LIBRARY PRTF_LIB VARCHAR(10) Name of the library that contains the printer file.

PRINTER_FILE PRTF VARCHAR(10) Name of the printer file.

SPOOLED_OUTPUT_QUEUE_LIBRARY OUTQ_LIB VARCHAR(10) Library containing output queue for spooled files.

Nullable Contains the null value if SPOOLED_OUTPUT_QUEUE is


*JOB.

SPOOLED_OUTPUT_QUEUE OUTQ VARCHAR(10) Output queue for spooled files. Can contain the following
special value:

*JOB The output queue for the job is used.

OWNER OWNER VARCHAR(10) The owner of the printer file

DEFINER DEFINER VARCHAR(10) The user who created the printer file.

CREATE_TIMESTAMP CREATED TIMESTAMP The time the printer file was created.

LAST_USED_TIMESTAMP LAST_USED TIMESTAMP The time the printer file was last used.

Nullable Contains the null value if the printer file has never been
used.

SIZE SIZE DECIMAL(15,0) The size of the printer file.

TEXT_DESCRIPTION TEXT VARCHAR(50) Descriptive text for the printer file.

Nullable Contains the null value if there is no text description.

954 IBM i: Performance and Query Optimization


Table 241. PRINTER_FILE_INFO view (continued)

Column name System column Data type Description


name

MAXIMUM_RECORDS MAXRCDS INTEGER The maximum number of records allowed in the spooled
file.
Nullable
Contains the null value if there is no maximum.

FILE_AVAILABLE FILEAVAIL VARCHAR(8) The time when a spooled file becomes available to an
output device for processing.

*FILEEND The file is available as soon as the file is


closed.

*IMMED The file is available as soon as the file is


opened.

*JOBEND The file is available when the job that owns


the file is completed.

COPIES COPIES INTEGER The number of copies for a spooled file.

HOLD HOLD VARCHAR(3) Hold spooled file.

NO Spooled file is not held.

YES Spooled file is held.

SAVE_AFTER_WRITE SAVE VARCHAR(3) Save spooled file after is is written.

NO Do not keep the spooled file.

YES Keep the spooled file.

OUTPUT_PRIORITY OUTPTY VARCHAR(4) For spooled output, the assigned priority on the output
queue. Can contain the following special value:

*JOB The output priority associated with the job that


created the spooled file is used.

USER_DATA USER_DATA VARCHAR(10) For spooled output, user-specified data that identifies the
file. Can contain the following special value:

*SOURCE If the spooled file was created by an


application program, the name of the
program is used. Otherwise, blanks are
used.

SPOOLED_FILE_OWNER SPOOL_OWN VARCHAR(10) For spooled output, the owner assigned to the spooled
file. Can contain the following special values:

*CURGRPPRF The spooled file is owned by the current


effective group profile of the current job
or thread.

*CURUSRPRF The spooled file is owned by the current


effective user of the current job or
thread.

*JOB The spooled file is owned by the original


user profile of the job.

*JOBGRPPRF The spooled file is owned by the group


profile of the original user profile of the
job.

FORM_TYPE FORM_TYPE VARCHAR(10) Type of form on which the output is printed.

PAGE_LENGTH PAGE_LEN DECIMAL(6,3) The page length, in lines per page, used by the spooled
file.

PAGE_WIDTH PAGE_WIDTH DECIMAL(6,3) The page width, in characters per printed line, used by the
spooled file.

LINES_PER_INCH LPI DECIMAL(3,1) The line spacing setting on the printer, in lines per inch.

CHARACTERS_PER_INCH CPI DECIMAL(3,1) The printer character density, in characters per inch.

Database performance and query optimization 955


Table 241. PRINTER_FILE_INFO view (continued)

Column name System column Data type Description


name

EXTERNALLY_DESCRIBED EXT_DESC VARCHAR(3) Externally described attribute.

NO File is not externally described.

YES File is externally described.

NUMBER_RECORD_FORMATS FORMATS INTEGER The number of record formats defined for the printer file

RECORD_FORMAT RCDFMT CLOB(1M) CCSID 1208 A list of record formats for the printer file. The value
is returned as a JSON array, with each array element
Nullable containing a JSON object with information for one format.
The array name is RCDFMT. The array elements consist of:
• The format name, with a key of FORMAT_NAME
• The number of fields in the format, with a key of
FORMAT_NUMBER_FIELDS
• The length of the format, with a key of
FORMAT_RECORD_LENGTH
• The format level ID, with a key of FORMAT_LEVEL_ID
• Descriptive text for the format, with a key of
FORMAT_TEXT
Contains the null value if record format information is not
available for this printer file.

Note
This function is provided in the SYSTOOLS schema as an example of returning information from a CL
command's OUTFILE. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source can be
extracted and used as a model for building similar helper functions, or to create a customized version
within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
• Look at some printer file attributes for printer files in library APPLIB1.

SELECT PRINTER_FILE, TEXT_DESCRIPTION, MAXIMUM_RECORDS, OUTPUT_PRIORITY, FORM_TYPE


FROM SYSTOOLS.PRINTER_FILE_INFO
WHERE PRINTER_FILE_LIBRARY = 'APPLIB1';

• Expand the list of record formats for printer file APPLIB1/INVOICE.

SELECT J.*
FROM SYSTOOLS.PRINTER_FILE_INFO,
JSON_TABLE(RECORD_FORMAT, 'lax $.RCDFMT'
COLUMNS (FORMAT_NAME VARCHAR(10),
FORMAT_FIELDS INTEGER,
FORMAT_LENGTH INTEGER,
FORMAT_LEVEL_ID CHAR(13),
FORMAT_TEXT VARCHAR(50)
)) J
WHERE PRINTER_FILE_LIBRARY = 'APPLIB1' AND PRINTER_FILE = 'INVOICE';

SPOOLED_FILE_DATA table function


The SPOOLED_FILE_DATA table function returns the content of a spooled file.
If the spooled file contains double byte data, the job CCSID must be a mixed CCSID.
Authorization: See Note below.

956 IBM i: Performance and Query Optimization


SPOOLED_FILE_DATA ( job-name
JOB_NAME =>

, spooled-file-name
SPOOLED_FILE_NAME =>

)
, spooled-file-number
SPOOLED_FILE_NUMBER =>

The schema is SYSTOOLS.

job-name A character string containing a qualified job name. Can contain the following special
value:

* Use the name of the current job.

spooled-file-name A character string containing the name of the spooled file. If this parameter is
omitted, QPJOBLOG is used.
spooled-file- The number of the spooled file. If this parameter is omitted, the spooled file with
number the highest number matching spooled-file-name is used.
The result of the function is a table containing a row for each record in the specified spooled file. The
columns of the result table are described in the following table. The result columns are nullable.
Table 242. SPOOLED_FILE_DATA table function

Column Name Data Type Description

ORDINAL_POSITION INTEGER Relative position of this row in the spooled file.

SPOOLED_DATA VARCHAR(200) The data for this row in the spooled file.

Note
This function is provided in the SYSTOOLS schema as an example of how spooled file data can be
returned by embedding the CPYSPLF CL command in an SQL table function. Similar to other Db2 for i
provided tools within SYSTOOLS, the SQL source can be extracted and used as a model for building similar
helper functions, or to create a customized version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
Return the most recent QSYSPRT file for a specific job:

SELECT * FROM TABLE(SYSTOOLS.SPOOLED_FILE_DATA(


JOB_NAME =>'193846/SLROMANO/QPADEV0009',
SPOOLED_FILE_NAME =>'QSYSPRT'))
ORDER BY ORDINAL_POSITION;

SPOOLED_FILE_INFO table function


The SPOOLED_FILE_INFO table function returns a list of spooled files on the system.
This information is similar to what is returned by the Work with Spooled Files (WRKSPLF) CL command
and the Open List of Spooled Files (QGYOLSPL) API.
Authorization: The caller must have:

Database performance and query optimization 957


• *EXECUTE authority to the library containing the output queue, and
• *USE authority to the output queue containing the spooled file.

SPOOLED_FILE_INFO (
user-name
USER_NAME =>

, starting-timestamp
STARTING_TIMESTAMP =>

, ending-timestamp
ENDING_TIMESTAMP =>

, status
STATUS =>

, job-name
JOB_NAME =>

, output-queue
OUTPUT_QUEUE =>

, user-data
USER_DATA =>

, form-type
FORM_TYPE =>

)
, system-name
SYSTEM_NAME =>

The schema is QSYS2.


Filtering on multiple values of user-name, output-queue, or user-data is slower.
Additionally, filtering on status is slower.

user-name A character string containing user profile names to filter on. The list can contain up to 20
values separated by blanks.
Can be one of the following special values:

*ALL The list is not filtered by user profile.


*CURRENT Spooled files owned by the current user profile are included in the list. This
is the default.

958 IBM i: Performance and Query Optimization


starting- A timestamp value for the earliest spooled file to return. If the parameter is omitted
timestamp or the null value, all spooled files with a create timestamp less than or equal to ending-
timestamp are returned.
ending- A timestamp value for the latest spooled file to return. If the parameter is omitted or
timestamp the null value, all spooled files with a create timestamp greater than or equal to starting-
timestamp are returned.
status A character string containing the spooled file status to filter on. The list can contain one or
more status values separated by blanks.

*ALL Spooled files are included in the list regardless of the current status. This
is the default.
*CLOSED The file has been completely processed by a program, but
SCHEDULE(*JOBEND) was specified. The job that produced the spooled
file has not finished.
*DEFERRED This spooled file has been deferred from printing.
*FINISHED This spooled file is no longer in the system. These spooled files are
included in the list of spooled files only if the qualified job name is
specified.
*HELD The file has been held.
*MESSAGE This file has a message that needs a reply or needs an action to be taken.
*OPEN The file has not been completely processed and is not ready to be
selected by a writer.
*PENDING This file is pending (waiting) to be printed.
*PRINTER The file has been completely sent to the printer, but the print complete
status has not been sent back.
*READY The file is available to be written to an output device by a writer.
*SAVED The file has been written and then saved. This file remains saved until it is
released.
*SENDING This spooled file is being sent or has been sent to a remote system.
*WRITING This file is currently being produced by the writer on an output device.

job-name A character string containing qualified job name.


Can be one of the following special values:

* The current job.


*ALL All jobs matching the other criteria are returned. This is the default.

output- A character string containing the name of the output queue to filter on. An output queue
queue name must be in the format library-name/outq-name. The list can contain up to 20 values
separated by blanks.
*LIBL or *CURLIB can be specified for the library name.
Instead of a list of qualified output queue names, the following special value can be used:

*ALL Spooled files are included in the list regardless of the output queue. This is the
default.

user-data A character string containing the value of the user-specified data or file name for spooled
files to filter on.
Can be the following special value:

Database performance and query optimization 959


*ALL Spooled files are included in the list regardless of the value for user-specified
data. This is the default.

form-type A character string containing the form type value to filter on.
Can be one of the following special values:

*ALL Spooled files are included in the list regardless of the value for form type. This is
the default.
*STD Only files that specify the standard form type are included in the list.

system- A character string containing the name of the system where the job that created the
name spooled file ran.
Can be one of the following special values:

*ALL The list is not filtered based on job system name. This is the default.
*CURRENT Only spooled files created on the current system are to be returned.

The result of the function is a table containing rows with the format shown in the following table. All
columns are nullable.
Table 243. SPOOLED_FILE_INFO table function

Column Name Data Type Description

SPOOLED_FILE_NAME VARCHAR(10) The name of the spooled file.

SPOOLED_FILE_NUMBER INTEGER The number of the spooled file.

STATUS VARCHAR(15) The status of the file.

CLOSED The file has been processed completely by


a program, but SCHEDULE(*JOBEND) was
specified. The job that produced the spooled file
has not finished.

DEFERRED Printing of the file has been deferred.

DELETED This spooled file is no longer in the system.


These spooled files are included in the list of
spooled files only if the qualified job name is
specified.

HELD The file has been held.

MESSAGE This file has a message which needs a reply or


WAITING an action to be taken.

OPEN The file has not been processed completely and


is not ready to be selected by a writer.

PENDING This file is pending (waiting) to be printed.

PRINTING The file has been completely sent to the printer,


but the print complete status has not been sent
back.

READY The file is available to be written.

SAVED The file has been written and then saved. This
file remains saved until it is released.

SENDING This spooled file is being sent or has been sent


to a remote system.

WRITING This file currently is being produced by the


writer on an output device.

OUTPUT_PRIORITY INTEGER The priority of the spooled file. The priority ranges from 1 (highest)
to 9 (lowest).
Contains the null value when STATUS is DELETED.

CREATION_TIMESTAMP TIMESTAMP(0) The timestamp, based on local job time, when the file was opened.

960 IBM i: Performance and Query Optimization


Table 243. SPOOLED_FILE_INFO table function (continued)

Column Name Data Type Description

USER_DATA VARCHAR(10) The user-specified data that describes the file.


Contains the null value if there is no user-specified data or STATUS
is DELETED.

SIZE BIGINT The spooled file size in bytes. The size of the spooled file is
the data stream size plus the spooled file's attributes, plus the
"overhead" storage used to store the spooled file's data stream.
Contains the null value if the size is not available or STATUS is
DELETED.

TOTAL_PAGES INTEGER The total number of pages or number of records for the spooled
file.
Contains the null value if the total number of pages is not available
or STATUS is DELETED.

COPIES INTEGER The number of copies remaining to print.


Contains the null value when STATUS is DELETED.

QUALIFIED_JOB_NAME VARCHAR(28) The qualified job name of the job that owns the spooled file.

JOB_NAME VARCHAR(10) The name of the job that owns the spooled file.

JOB_USER VARCHAR(10) The name of the user that owns the spooled file.

JOB_NUMBER VARCHAR(6) The number of the job that owns the spooled file.

FILE_AVAILABLE VARCHAR(8) The schedule of the spooled file.

*IMMED The spooled file is schedule immediate. A spooling


writer can process the spooled file immediately.

*FILEEND The spooled file is schedule file end. A spooling


writer cannot process the spooled file until it has
been closed.

*JOBEND The spooled file is schedule job end. A spooling


writer cannot process the spooled file until the job
of the spooled file has ended.

FORM_TYPE VARCHAR(10) Spooled file form type. The type of form to load in the printer to
print this file.
Contains the null value when STATUS is DELETED.

OUTPUT_QUEUE_LIBRARY VARCHAR(10) The library where the output queue is located.


Contains the null value when STATUS is DELETED.

OUTPUT_QUEUE VARCHAR(10) The name of the output queue in which the spooled file is located.
Contains the null value when STATUS is DELETED.

ASP_NUMBER INTEGER The auxiliary storage pool in which the spooled file resides.
Contains the null value when STATUS is DELETED.

SYSTEM VARCHAR(8) The name of the system where the job that created the spooled file
ran.

INTERNET_PRINT_PROTOCOL_JOB_ID INTEGER The IPP job identifier assigned by the system based on the output
queue to which the file was added or moved. This value ranges
from 1 to 2147483647 and is not guaranteed to be unique for a
given output queue.
Contains the null value when STATUS is DELETED.

Example
• List all the spooled files for the current job.

SELECT * FROM TABLE(QSYS2.SPOOLED_FILE_INFO(JOB_NAME => '*'));

Storage Services
These views provide information about storage and storage devices.

Database performance and query optimization 961


ADD_DEVICE_LOCKING_POLICY procedure
The ADD_DEVICE_LOCKING_POLICY procedure adds a specific NVMe device, or all eligible NVMe
devices, to the password policy.
Authorization: The caller must have *IOSYSCFG and *SERVICE special authorities.

ADD_DEVICE_LOCKING_POLICY ( policy-password
POLICY_PASSWORD =>

, resource-name )
RESOURCE_NAME =>

The schema is QSYS2.

policy- A character string that contains the policy password. It must be at least 8 characters
password long and cannot exceed 32 characters.
resource-name A character string that contains the resource name of the NVMe device to be added to
the locking policy.
The following special value can be specified:

*ALL All NVMe devices that have a namespace configured are added to the locking
policy.

Example
• Add a new device to the locking policy.

CALL QSYS2.ADD_DEVICE_LOCKING_POLICY(POLICY_PASSWORD => 'My0dev9pw!',


RESOURCE_NAME => 'UNIT2');

ASP_INFO view
The ASP_INFO view returns information about auxiliary storage pools (ASPs).
The values returned for the columns in the view are similar to the values returned by the Work with
Configuration Status (WRKCFGSTS) CL command and the Open List of ASPs (QYASPOL) API.
Authorization: None required.
The following table describes the columns in the view. The system name is ASP_INFO. The schema is
QSYS2.
Table 244. ASP_INFO view

Column Name System Column Name Data Type Description

DEVICE_DESCRIPTION_NAME DEVD_NAME VARCHAR(10) The name of the device description that most
Nullable recently brought the independent ASP (IASP) to
varyon/active state.
Contains the null value if the ASP is not an IASP.

ASP_NUMBER ASP_NUM INTEGER A unique identifier for an ASP. Possible values are 1
through 255.

1 The system ASP

2-32 User ASPs

33-255 IASPs

962 IBM i: Performance and Query Optimization


Table 244. ASP_INFO view (continued)

Column Name System Column Name Data Type Description

ASP_STATE ASP_STATE VARCHAR(10) The device configuration status of an ASP.

ACTIVE The status of the ASP is active.

AVAILABLE The status of the ASP is available.

FAILED The status of the ASP is failed.

NONE There is no status. This value is


used for the system ASP and any
basic user ASPs.

VARIED OFF The status of the ASP is varyoff.

VARIED ON The status of the ASP is varyon.

ASP_TYPE ASP_TYPE VARCHAR(9) The use that is assigned to the ASP.


Nullable
PRIMARY The ASP is a primary ASP.

SECONDARY The ASP is a secondary ASP.

SYSTEM The ASP is the system ASP.

UDFS The ASP is a user-defined file


system ASP.

USER The ASP is a user ASP.

Contains the null value for an IASP when the type


cannot be determined.

RDB_NAME RDB_NAME VARCHAR(18) The name that is assigned to the database that this
Nullable ASP defines.
Contains the null value if ASP_TYPE is UDFS or
USER.

NUMBER_OF_DISK_UNITS DISK_UNITS INTEGER The total number of disk units in the ASP. If
mirroring is active for disk units within the ASP, the
mirrored pair of units is counted as one.

DISK_UNITS_PRESENT PRESENT VARCHAR(4) Indicates whether disk units in the ASP were found.

ALL All disk units were found.

NONE No disk units were found.

SOME The disk unit that is used to provide the


identity of the ASP was found but some
other disk units were not found.

ENCRYPTED_ASP ENCRYPTED VARCHAR(3) Whether the data contained in the ASP is encrypted.

NO The data in the ASP is not encrypted.

YES The data in the ASP is encrypted.

TOTAL_CAPACITY TOTCAP BIGINT The total number of used and unused megabytes in
Nullable the ASP. A special value of -2 is returned if the size
of this field is exceeded.
Contains the null value if the capacity cannot be
determined.

TOTAL_CAPACITY_AVAILABLE TOTCAPA BIGINT The total number of unused megabytes in the ASP.
Nullable A special value of -2 is returned if the value was too
big to return.
Contains the null value if the capacity cannot be
determined.

PROTECTED_CAPACITY PROTCAP BIGINT The total number of used and unused megabytes in
Nullable the ASP that are protected by mirroring or device
parity. A special value of -2 is returned if the value
was too big to return.
Contains the null value if the capacity cannot be
determined.

Database performance and query optimization 963


Table 244. ASP_INFO view (continued)

Column Name System Column Name Data Type Description

PROTECTED_CAPACITY_AVAILABLE PROTCAPA BIGINT The number of unused megabytes in the ASP that
Nullable are protected by mirroring or device parity. A special
value of -2 is returned if the value was too big to
return.
Contains the null value if the capacity cannot be
determined.

UNPROTECTED_CAPACITY UNPROTCAP BIGINT The total number of used and unused megabytes in
Nullable the ASP that are not protected by mirroring or device
parity. A special value of -2 is returned if the value
was too big to return.
Contains the null value if the capacity cannot be
determined.

UNPROTECTED_CAPACITY_ UNPROTCAPA BIGINT The number of unused megabytes in the ASP that
AVAILABLE Nullable are not protected by mirroring or device parity. A
special value of -2 is returned if the value was too
big to return.
Contains the null value if the capacity cannot be
determined.

SYSTEM_STORAGE SYS_STG INTEGER The amount of storage in megabytes currently


Nullable allocated in the ASP for operating system use.

OVERFLOW_STORAGE OVER_STG BIGINT The number of megabytes of storage that has


Nullable overflowed from the user ASP into the system ASP.
A special value of -2 is returned if the value was too
big to return.
Contains the null value if this is an IASP.

STORAGE_THRESHOLD_PERCENTAGE THRESHOLD INTEGER When the storage in the ASP reaches this
percentage, a warning message is sent to the
QSYSOPR message queue. When this percentage
is reached for the system ASP (ASP 1), message
CPF0907 is sent. When this percentage is reached
for a user ASP, message CPI0953 is sent.

OVERFLOW_RECOVERY_RESULT OVER_RES VARCHAR(7) An indicator of the result of the ASP overflow


Nullable recovery operation, which is performed during
IPL at the user's request. When this operation
is requested, an attempt is made to recover the
user ASP from an overflow condition by moving
overflowed auxiliary storage from the system
ASP back to the user ASP during the storage
management recovery step of an IPL.

CANCEL ASP overflow recovery was canceled


prior to completion.

FAIL ASP overflow recovery failed due to


insufficient space in the user ASP.

SUCCESS All overflowed storage was


successfully moved.

Contains the null value if this is an IASP.

ERROR_LOG_SPACE ERR_SPACE INTEGER The number of megabytes of auxiliary storage


Nullable allocated to the error log.
Contains the null value if this is not the system ASP.

MACHINE_LOG_SPACE LOG_SPACE INTEGER The number of megabytes of auxiliary storage


Nullable allocated to the machine log.
Contains the null value if this is not the system ASP.

MACHINE_TRACE_SPACE TRC_SPACE INTEGER The number of megabytes of auxiliary storage


Nullable allocated to the machine trace.
Contains the null value if this is not the system ASP.

MAIN_STORAGE_DUMP_SPACE MSD_SPACE INTEGER The number of megabytes of auxiliary storage


Nullable allocated to the main storage dump space.
Contains the null value if this is not the system ASP.

964 IBM i: Performance and Query Optimization


Table 244. ASP_INFO view (continued)

Column Name System Column Name Data Type Description

MICROCODE_SPACE MIC_SPACE INTEGER The number of megabytes of auxiliary storage


Nullable allocated to the microcode and space used by the
microcode.
Contains the null value if this is an IASP that is
varied off.

END_IMMEDIATE END_IMMED VARCHAR(3) This column only applies to the system ASP (ASP 1).
Nullable
NO If a request for space in the system ASP
cannot be satisfied because there is not
enough storage, the system will be allowed
to continue running.

YES If a request for space in the system ASP


cannot be satisfied because there is not
enough storage, the system will be ended
immediately.

Contains the null value if this is not the system ASP.

COMPRESSION_RECOVERY_POLICY COMP_RECOV VARCHAR(18) The compression recovery policy for the ASP. If
the ASP has compressed drives as part of its
configuration, this value controls how overflow
situations are handled for this ASP. The following
policies allow the user to control what is done when
the ASP appears full.

OVERFLOW When the ASP capacity is about to


DELAY be exceeded, the operating system
posts system reference code (SRC)
A6xx 0277 in the system control
panel and waits for a limited time
for space to become available. If
space becomes available before
the limited time ends, the SRC is
removed from the system control
panel and normal operations
resume. If space does not become
available before the limited time
ends, data overflows into the
system ASP.

OVERFLOW When the ASP capacity is about to


IMMEDIATE be exceeded, the data immediately
overflows into the system ASP.

WAIT When the ASP capacity is about


to be exceeded, the operating
system posts SRC A6xx 0277 in
the system control panel and waits
indefinitely for space to become
available. The user must take
action before normal operation
resumes. Possible actions include
deleting objects from the ASP
or changing the compression
recovery policy to a value that
allows the ASP to overflow.

COMPRESSED_DISK_UNITS COMPRESSED VARCHAR(4) Whether there are compressed disk units in the ASP.

ALL All disk units in this ASP are compressed.

NONE No compressed disk units in this ASP.

SOME Compressed and uncompressed disk units


in this ASP.

CHANGES_WRITTEN_TO_DISK WRITTEN VARCHAR(3) An indicator of whether all changes made the


previous time the IASP was online were written to
disk. Varyoff processing attempts to write changed
IASP storage but, in some failures, it may not be
successful.

NO Not all changes were written to disk.

YES All changes were written to disk.

Database performance and query optimization 965


Table 244. ASP_INFO view (continued)

Column Name System Column Name Data Type Description

MULTIPLE_CONNECTION_DISK_UNITS MULT_CONN VARCHAR(3) A disk unit may have multiple resource names.
Each resource name represents a unique connection
to the disk unit. All active connections are used
to communicate with the disk unit. This attribute
indicates whether the disk unit has more than one
connection.

NO The disk unit has only one connection.

YES The disk unit has more than one connection.

BALANCE_STATUS BALANCE VARCHAR(8) The current status of the balance function for this
Nullable ASP.

COMPLETE The ASP balance function has


completed running. The ASP is
completely balanced.

ENDED The ASP balance function has run,


but was ended before the ASP
was completely balanced. The Start
ASP Balance (STRASPBAL) command
can be used to restart the balance
function.

ENDING The ASP balance function is currently


in the process of ending. Either
the time limit has run out or
the End ASP Balance (ENDASPBAL)
command was issued for this ASP.

NONE No balance activity has occurred for


this ASP.

RUNNING The ASP balance function is currently


running for this ASP.

Contains the null value if ASP_STATE is not ACTIVE


or AVAILABLE for IASP.

966 IBM i: Performance and Query Optimization


Table 244. ASP_INFO view (continued)

Column Name System Column Name Data Type Description

BALANCE_TYPE BAL_TYPE VARCHAR(21) The type of balance activity that is currently running
Nullable or was done last.

CAPACITY Capacity balancing. Capacity


BALANCING balancing redistributes data so
that the percentage of disk space
used is the same on all disk units
within the ASP.

CLEAR Clear collection data. Clear


COLLECTION collection data removes the trace
DATA data created by running the
Trace ASP Balance (TRCASPBAL)
command.

HSM Hierarchical Storage Management


BALANCING (HSM) balancing. HSM balancing
can be run only on an
ASP that contains a mixture
of high-performance and low-
performance disk units. An
example of low-performance
disk units is compressed disk
units. The HSM balance function
moves high-use data to high-
performance units and moves
low-use data to low-performance
units. The high-use and low-use
data is identified by running the
Trace ASP Balance (TRCASPBAL)
command.

MOVE DATA Move data. Move data is used


to reduce the down time
associated with removing a disk
unit. The Check ASP Balance
(CHKASPBAL) command can be
used to determine which units
are currently marked to no longer
receive new allocations and to
have their existing allocations
moved to other disk units.

MP Media Preference (MP) balancing.


BALANCING MP balancing can be run only on
an ASP that contains a mixture of
Solid State Disk (SSD) units and
Hard Disk Drive (HDD) units. The
goal of the MP balance function
is to have high-use data on SSD
units and low-use data on HDD
units. The high-use and low-use
data is identified by running the
Trace ASP Balance (TRCASPBAL)
command.

NONE No ASP balance activity was


requested for the ASP.

USAGE Usage balancing. Usage balancing


BALANCING redistributes data so that the
percentage of disk activity is
the same on all disk units
within the ASP. High-use and
low-use data is identified by
running the Trace ASP Balance
(TRCASPBAL) command. Usage
balancing moves data among the
disk units, guided by the trace
results, in an attempt to equalize
the utilizations.

Contains the null value if ASP_STATE is not ACTIVE


or AVAILABLE for IASP.

Database performance and query optimization 967


Table 244. ASP_INFO view (continued)

Column Name System Column Name Data Type Description

BALANCE_DATA_MOVED BAL_MOVED BIGINT The number of megabytes that have been moved
Nullable by the balance function. A special value of -2 is
returned if the value was too big to return.
Contains the null value if BALANCE_STATUS is not
RUNNING.

BALANCE_DATA_REMAINING BAL_REMAIN BIGINT The number of megabytes that remain to be


Nullable moved by the balance function before the move
is considered complete. A special value of -2 is
returned if the value was too big to return.
Contains the null value if BALANCE_STATUS is not
RUNNING.

BALANCE_TIMESTAMP BAL_TIME TIMESTAMP(0) The timestamp of the last status change for the
Nullable balance function.
Contains the null value when BALANCE_TYPE is
NONE or the null value.

TRACE_STATUS TRC_STATUS VARCHAR(10) The current status of the trace function. The trace
Nullable gathers statistics about the data on the disk units
within the ASP. This data is used by the balance
functions.

CLEARING The trace data for this ASP is being


cleared.

COMPLETE 1 The trace function has completed


running. The statistics for the ASP
have been gathered and are ready
for the balance function to start.

COMPLETE 2 The trace function has completed


and the statistics for the ASP have
been gathered. The ASP is ready
for further collection or for the
balance function to start.

ENDING The trace function is currently in


the process of ending. Either the
time limit has run out or the trace
was stopped through use of the
Trace ASP Balance (TRCASPBAL)
command.

NONE There is no current trace data for


this ASP.

RUNNING The trace function is currently


running for this ASP.

Contains the null value if ASP_STATE is not ACTIVE


or AVAILABLE for IASP.

TRACE_DURATION TRC_DUR INTEGER The number of minutes that the trace function has
Nullable run collecting data for this ASP. The trace can be run
multiple times for an ASP.
Contains the null value when TRACE_STATUS is
NONE or the null value.

TRACE_TIMESTAMP TRC_TIME TIMESTAMP(0) The timestamp of the last status change for the
Nullable trace function.
Contains the null value when TRACE_STATUS is
NONE or the null value.

GEOGRAPHIC_MIRROR_ROLE GEO_ROLE VARCHAR(10) The current role of the geographically mirrored IASP.
Nullable
DETACHED System owns a detached mirror
copy.

MIRROR System owns the mirror copy.

PRODUCTION System owns the production copy.

UNKNOWN The geographic mirror role is


unknown.

Contains the null value if geographic mirroring is not


configured.

968 IBM i: Performance and Query Optimization


Table 244. ASP_INFO view (continued)

Column Name System Column Name Data Type Description

GEOGRAPHIC_MIRROR_MODE GEO_MODE VARCHAR(12) The performance mode of the geographic mirroring.


Nullable
ASYNCHRONOUS Control is returned to
the application before the
mirrored write actually makes
it to the mirror copy.

SYNCHRONOUS Data is mirrored before write


operations complete on the
production system.

UNKNOWN The performance mode is not


known.

Contains the null value if geographic mirroring is not


configured.

GEOGRAPHIC_MIRROR_COPY_STATE GEO_CSTATE VARCHAR(14) The mirror state of the geographic mirror copy.
Nullable
ACTIVE Geographic mirroring is actively
replicating.

RESUME The system will attempt to


PENDING perform geographic mirroring
when the IASP is online.

RESUMING The system is resuming and the


IASP is online and performing
synchronization..

SUSPENDED The geographic mirroring mirror


copy is suspended and
geographic mirroring is not being
performed.

UNKNOWN The mirror copy state is not


known.

Contains the null value if geographic mirroring is not


configured.

GEOGRAPHIC_MIRROR_DATA_STATE GEO_DSTATE VARCHAR(12) The condition of the data on the geographic mirror
Nullable copy.

INCOHERENT There is incoherent data in the


mirror copy and the data cannot
be used.

SYNCHRONIZED The remote copy is in sync with


the production copy.

UNKNOWN The state of the data is not


known.

USABLE The remote copy contains


usable data. A detached mirror
copy always has this state.

Contains the null value if geographic mirroring is not


configured.

GEOGRAPHIC_MIRROR_RESUME_PRIORITY GEO_RESUME VARCHAR(7) The priority given to resynchronize the geographic


Nullable mirror production copy with the mirror copy
following a suspend.

HIGH This priority completes


synchronization as quickly as
possible, but consumes the most
resources.

LOW This priority uses the fewest


resources, but synchronization will
take longer to complete.

MEDIUM This priority provides a balance


between resource usage and time to
synchronization completion.

UNKNOWN The priority is not known.

Contains the null value if geographic mirroring is not


configured.

Database performance and query optimization 969


Table 244. ASP_INFO view (continued)

Column Name System Column Name Data Type Description

GEOGRAPHIC_MIRROR_SUSPEND_TIMEOUT GEO_WAIT INTEGER The number of seconds the production node waits
for a response from the mirror copy node before
suspending geographic mirroring.
Contains the null value if geographic mirroring is not
configured.

GEOGRAPHIC_MIRROR_TRANSMISSION_ GEO_TCOMP VARCHAR(15) Indicates whether geographic mirror data is


COMPRESSION compressed when sent between systems.

NONE Data is not compressed.

SYNCHRONIZATION Data is compressed


during a full or partial
synchronization.

Contains the null value if geographic mirroring is not


configured.

RESOURCE_NAME RESOURCE VARCHAR(10) The resource name that identifies the ASP by which
Nullable a collection of disks is known.
Contains the null value for the system ASP, any user
ASPs, and for an IASP where the name cannot be
determined.

PRIMARY_ASP_RESOURCE_NAME PRIMARY VARCHAR(10) The resource name of the primary ASP for a
Nullable secondary ASP.
Contains the null value if ASP_TYPE is not
SECONDARY.

ACCESS_PATH_TARGET_ SMAPP VARCHAR(7) The time, in minutes, targeted for access path
RECOVERY_TIME protection for this ASP.
Nullable
1-1440 The number of minutes set for the
system access path recovery time.

*NONE No system access path recovery time


is set. The access paths for this ASP
are protected only if they need to be
protected to reach the system access
path recovery time.

*MIN All of the eligible access paths for this


ASP are protected. The system uses the
minimum time needed for access path
recovery.

Contains the null value when system-managed


access path protection is off, if the user does not
have *JOBCTL authority, or if this is an IASP that is
varied off.

ACCESS_PATH_ESTIMATED_ AP_RECOV INTEGER The amount of time, in minutes, that the system will
RECOVERY_TIME take to recover the access paths during the vary on
Nullable of this independent storage pool (IASP). This value
assumes that all access paths that are protected are
recovered during vary on of the IASP.
The estimated system access path recovery time is
influenced by the include access paths setting for
the system.
• If the include access paths setting is *ELIGIBLE,
this value is the estimated system access path
recovery time of all the eligible access paths that
are not chosen for protection.
• If the include access paths setting is *ALL,
this value is the estimated system access path
recovery time of all the eligible access paths that
are not chosen for protection plus all the access
paths that are not eligible for protection.
Contains the null value when system-managed
access path protection is off, if the user does not
have *JOBCTL authority, or if this is an IASP that is
varied off.

970 IBM i: Performance and Query Optimization


Table 244. ASP_INFO view (continued)

Column Name System Column Name Data Type Description

SMAPP_DISK_STORAGE_USED SMAPP_STG BIGINT The total amount of auxiliary disk storage, in


megabytes, used by internal objects that are
Nullable used exclusively for system-managed access path
protection (SMAPP) for this IASP.
Contains the null value when system-managed
access path protection is off, if the user does not
have *JOBCTL authority, or if this is an IASP that is
varied off.

Example
• Show ASP information for the partition.

SELECT * FROM QSYS2.ASP_INFO;

ASP_JOB_INFO view
The ASP_JOB_INFO view returns information about active jobs that are using an independent auxiliary
storage pool (IASP).
The information is similar to what is returned by the Work with ASP Jobs (WRKASPJOB) CL command.
Authorization: None required to see information for jobs where the caller's user profile is the same as the
job user identity of the job for which the information is being returned. Otherwise, the caller must have
*JOBCTL special authority, or be authorized to the QIBM_DB_SQLADM or QIBM_DB_SYSMON function
usage identifiers.
The following table describes the columns in the view. The system name is ASPJ_INFO. The schema is
QSYS2.
Table 245. ASP_JOB_INFO view

Column Name System Column Name Data Type Description

IASP_NAME IASP_NAME VARCHAR(10) The name of the independent ASP (IASP) device description.

IASP_NUMBER IASPNUM INTEGER The number associated with the ASP device.

JOB_NAME JOB_NAME VARCHAR(28) The qualified job name.

JOB_STATUS JOB_STATUS VARCHAR(4) The status of the initial thread of the job.
Nullable For the list of values see Work Management API Attribute
Descriptions in Application Programming Interfaces and search
on "Active job status".

JOB_TYPE JOB_TYPE VARCHAR(3) Type of active job.


Nullable
ASJ Autostart

BCH Batch

BCI Batch Immediate

EVK Started by a procedure start request

INT Interactive

M36 Advanced 36 server job

MRT Multiple requester terminal

PDJ Print driver job

PJ Prestart job

RDR Spool reader

SBS Subsystem monitor

SYS System

WTR Spool writer

Database performance and query optimization 971


Table 245. ASP_JOB_INFO view (continued)

Column Name System Column Name Data Type Description

AUTHORIZATION_NAME USER_NAME VARCHAR(10) The user profile under which the initial thread is running at this
Nullable time.

SUBSYSTEM_NAME SUB_NAME VARCHAR(10) Name of subsystem where job is running.


Nullable

SQL_STATEMENT_STATUS SQL_STATUS VARCHAR(8) The status of SQL within this job.


Nullable
ACTIVE An SQL statement is currently running

COMPLETE At least one SQL statement has run and has


completed

Contains the null value if no SQL statement has been run.

SQL_STATEMENT_TEXT SQL_STMT VARCHAR(10000) Statement text of the last SQL statement to run or the SQL
Nullable statement that is currently running. The statement text will be
truncated if it is longer than the column.
Contains the null value if no SQL statement has been run.

SQL_STATEMENT_START_ SQL_TIME TIMESTAMP The timestamp of the execution start for an active SQL
TIMESTAMP Nullable statement.
Contains the null value if there is no active SQL statement.

ASP_TYPE ASP_TYPE VARCHAR(9) The use that is assigned to the ASP.


Nullable
PRIMARY The ASP is a primary ASP.

SECONDARY The ASP is a secondary ASP.

UDFS The ASP is a user-defined file system ASP.

RDB_NAME RDB_NAME VARCHAR(18) The name that is assigned to the database that this ASP defines.
Nullable Contains the null value if ASP_TYPE is not PRIMARY or
SECONDARY.

Example
List all the jobs that are active for IASP33.

SELECT JOB_NAME, JOB_STATUS, JOB_TYPE, AUTHORIZATION_NAME


FROM QSYS2.ASP_JOB_INFO
WHERE IASP_NAME = 'IASP33';

ASP_VARY_INFO view
The ASP_VARY_INFO view returns one row for each step associated with a vary on or vary off operation for
all independent ASP devices.
The values returned for the columns in the view are similar to the values returned by the Display ASP
Status (DSPASPSTS) CL command.
Authorization: The caller must have *USE authority to the independent ASP device description.
The following table describes the columns in the view. The system name is VARY_INFO. The schema is
QSYS2.
Table 246. ASP_VARY_INFO view

Column Name System Column Name Data Type Description

IASP_NAME IASP_NAME VARCHAR(10) The name of the ASP device description.

OPERATION_NUMBER OP_NUMBER INTEGER A value for an instance of a vary on or vary off


operation, where the highest number is the most
recent operation. The most recent 64 operations
are returned.

972 IBM i: Performance and Query Optimization


Table 246. ASP_VARY_INFO view (continued)

Column Name System Column Name Data Type Description

OPERATION_TYPE OP_TYPE VARCHAR(8) The type of vary operation.

VARY OFF

VARY ON

OPERATION_STATE OP_STATE VARCHAR(8) The state of the entire operation.

ACTIVE The operation is active.


STEP_STATE shows the status of
the steps that are part of the
operation.

COMPLETE The operation completed


successfully.

FAILED The operation failed to complete


successfully.

STEP STEP VARGRAPHIC(50) The description of the operation step.


CCSID 1200

STEP_STATE STEP_STATE VARCHAR(8) The state of the operation step.

ACTIVE The step is active.

COMPLETE The step completed successfully.

FAILED The step failed to complete


successfully.

START_TIMESTAMP START TIMESTAMP The timestamp for the start of this operation step.

END_TIMESTAMP END TIMESTAMP The timestamp for the end of this operation step.
Nullable Contains the null value if the operation step has
not completed or may never complete.

DURATION DURATION DECIMAL(12,6) The time duration, in seconds, of this operation


Nullable step.
Contains the null value if the operation step has
not completed or may never complete.

JOB_NAME JOB_NAME VARCHAR(28) The qualified job name that initiated this vary
Nullable operation.
Contains the null value if the job name is not
available.

IASP_NUMBER IASPNUM INTEGER The number associated with the ASP device.

Example
• Return the steps from available vary on operations, listed from most expensive to least expensive.

SELECT * FROM QSYS2.ASP_VARY_INFO


WHERE OPERATION_TYPE = 'VARY ON'
ORDER BY IASP_NAME, DURATION DESC;

• Create a table to retain vary on historical data. Populate it with the current available values.

CREATE TABLE VARY_HISTORY AS


(SELECT * FROM QSYS2.ASP_VARY_INFO) WITH DATA;

• Update the table that contains vary on historical data with any new rows.

MERGE INTO VARY_HISTORY H


USING QSYS2.ASP_VARY_INFO N
ON H.OPERATION_NUMBER = N.OPERATION_NUMBER
WHEN NOT MATCHED THEN
INSERT VALUES (N.IASP_NAME, N.OPERATION_NUMBER, N.OPERATION_TYPE,
N.OPERATION_STATE, N.STEP, N.STEP_STATE,
N.START_TIMESTAMP, N.END_TIMESTAMP, N.DURATION,
N.JOB_NAME, N.IASP_NUMBER);

Database performance and query optimization 973


CHANGE_DEVICE_LOCKING_POLICY procedure
The CHANGE_DEVICE_LOCKING_POLICY procedure changes the password policy for all NVMe devices.
Authorization: The caller must have *IOSYSCFG and *SERVICE special authorities.

CHANGE_DEVICE_LOCKING_POLICY (

policy-password ,
POLICY_PASSWORD =>

new-policy-password ,
NEW_POLICY_PASSWORD =>

)
fixup
FIXUP =>

The schema is QSYS2.

policy- A character string that contains the current device policy password used to unlock the
password device.
If policy-password is specified, new-policy-password must also be provided.
new-policy- A character string that contains the new policy password used to unlock the device and for
password changing the locking policy configuration.
It must be at least 8 characters long and cannot exceed 32 characters.
If new-policy-password is specified, policy-password must also be provided.
fixup A character string that indicates whether the NVMe device is to be resynchronized with the
password stored in Platform KeyStore (PKS).
The NVMe device must be under the locking policy.
This option should only be used when the PASSWORD_FIXUP_REQUIRED column in the
QSYS2.LOCKING_POLICY_INFO view has a value of YES.

YES The NVMe device is to be resynchronized with the password stored in PKS.
If fixup is YES, new-policy-password and policy-password must not be specified.

Example
• Change a locking policy password for the current device.

CALL QSYS2.CHANGE_DEVICE_LOCKING_POLICY(POLICY_PASSWORD => 'My0dev9pw!',


NEW_POLICY_PASSWORD => 'changeit58');

CHANGE_DISK_PATHS procedure
The CHANGE_DISK_PATHS procedure enables or disables all paths matching the parameters provided.
The last path to a disk will not be disabled unless explicitly requested. This procedure is only supported
for some external SCSI devices.
Any combination of resource-name, host-wwpn, remote-wwpn, and adapter-name can be specified. The
specified operation will be applied to all the paths that match the provided parameters. A disable
operation must leave at least one remaining active path to all resources unless the force parameter with a
value of YES is specified. If no paths match the provided parameters, no action is taken.

974 IBM i: Performance and Query Optimization


The world-wide port name (WWPN) values that can be changed by this procedure apply to an IO Adapter
(IOA).
Authorization: The caller must have *IOSYSCFG special authority.

CHANGE_DISK_PATHS ( operation
OPERATION =>

, resource-name
RESOURCE_NAME =>

, host-wwpn
HOST_WWPN =>

, remote-wwpn
REMOTE_WWPN =>

, force
FORCE =>

)
, adapter-name
ADAPTER_NAME =>

The schema is QSYS2.

operation A character string that contains the operation to perform.

DISABLE Disable all paths matching the parameters.


ENABLE Enable all paths matching the parameters.

resource- A character string that contains the resource name of the path to be changed. If resource-
name name is omitted or the null value, the operation will be applied to all the paths that match
the world wide port name or adapter parameters that are provided.
host-wwpn A 16 character hexadecimal string representing the world wide port name for the host side
of the paths to be enabled or disabled. If resource-name, remote-wwpn, or adapter-name
is specified, this parameter can be omitted or have the null value.
If this parameter is not specified, the default is the null value, meaning that host-wwpn is
not part of the request.

remote- A 16 character hexadecimal string representing the world wide port name for the remote
wwpn side of the paths to be enabled or disabled. If resource-name, host-wwpn, or adapter-
name is specified, this parameter can be omitted or have the null value.
If this parameter is not specified, the default is the null value, meaning that remote-wwpn
is not part of the request.

force A character string that indicates whether the last path to a disk can be disabled by this
procedure.

NO The last path to a disk will never be disabled. This is the default.
YES The last path to a disk can be disabled, overriding normal safely checks.

Database performance and query optimization 975


adapter- A character string that specifies an adapter on which all paths should be disabled. If
name resource-name, host-wwpn, or remote-wwpn is specified, this parameter can be omitted or
have the null value.
If this parameter is not specified, the default is the null value, meaning that adapter-name
is not part of the request.

v
• Enable a path.

CALL QSYS2.CHANGE_DISK_PATHS(OPERATION => 'ENABLE',


RESOURCE_NAME => 'DMP001');

• Enable all paths on a host port.

CALL QSYS2.CHANGE_DISK_PATHS(OPERATION => 'ENABLE',


HOST_WWPN => 'c050760a3038001e');

• Disable a path.

CALL QSYS2.CHANGE_DISK_PATHS(OPERATION => 'DISABLE',


RESOURCE_NAME => 'DMP001');

• Disable a path, forcing the disk to be disabled if it is the last path to the disk.

CALL QSYS2.CHANGE_DISK_PATHS(OPERATION => 'DISABLE',


RESOURCE_NAME => 'DMP001',
FORCE => 'YES');

• Disable all paths on a host target pair.

CALL QSYS2.CHANGE_DISK_PATHS(OPERATION => 'DISABLE',


HOST_WWPN => 'c050760a3038001e',
REMOTE_WWPN => '5005076306181347');

• Disable all paths on a remote port.

CALL QSYS2.CHANGE_DISK_PATHS(OPERATION => 'DISABLE',


REMOTE_WWPN => '5005076306181347');

• Enable all paths on an adapter.

CALL QSYS2.CHANGE_DISK_PATHS(OPERATION => 'ENABLE',


ADAPTER_NAME => 'DC06');

• Enable all paths on an adapter to a specific remote port.

CALL QSYS2.CHANGE_DISK_PATHS(OPERATION => 'ENABLE',


REMOTE_WWPN => '5005076306181347',
ADAPTER_NAME => 'DC06');

• Disable all paths on an adapter.

CALL QSYS2.CHANGE_DISK_PATHS(OPERATION => 'DISABLE',


ADAPTER_NAME => 'DC06');

• Disable all paths on an adapter to a specific remote port.

CALL QSYS2.CHANGE_DISK_PATHS(OPERATION => 'DISABLE',

976 IBM i: Performance and Query Optimization


REMOTE_WWPN => '5005076306181347',
ADAPTER_NAME => 'DC06');

CREATE_LOCKING_POLICY procedure
The CREATE_LOCKING_POLICY procedure creates a password policy.
Prior to creating a password policy, the Platform KeyStore must be enabled through the HMC’s Partition
Properties -> Advanced Settings -> Platform KeyStore Size value must be set to a non-zero value.
Before creating the NVMe password protection policy on the partition, it is recommended that all of the
system and user data be saved using GO SAVE: Option 21 (saving the entire system).
All NVMe devices supported by IBM i are Self-Encrypting Drives (SED). This means the data is encrypted
at rest. However, the key used to encrypt and decrypt the data is not protected. By creating a password
policy and adding NVMe devices to it, the devices can protect the confidentiality of stored user data
against unauthorized access once the device leaves the owner’s control. This feature uses the Trusted
Computer Group (TCG) Opal Security Subsystem Class (SSC) specification for storage. Each NVMe device
that supports the Opal SSC is registered in a list of devices on which the administrator can establish a
locking policy. Once the device is added to the locking policy the NVMe device will lock itself when Main
Power loss or PCIe cold resets occur.
The NVMe device will be locked when:
• DLPAR Remove operation is performed on the device
• Concurrent Maintenance Power Off is performed on the device
• The partition is IPLed
• When the NVMe device is reset
Once the device is locked, reads and writes issued to the drive will fail. While the NVMe device remains
in the partition, restoring power to the device will cause it to automatically unlock itself, using the policy
password stored in the Platform KeyStore.
Authorization: The caller must have *IOSYSCFG and *SERVICE special authorities.

CREATE_LOCKING_POLICY ( policy-password )
POLICY_PASSWORD =>

The schema is QSYS2.

policy- A character string that contains the initial policy password that will be used to unlock
password the device(s) and for changing the locking policy configuration.
It must be at least 8 characters long and cannot exceed 32 characters.

Example
• Create a locking policy and add all configured NVMe devices to the policy.

CALL QSYS2.CREATE_LOCKING_POLICY(POLICY_PASSWORD => 'My0dev9pw!');

DELETE_LOCKING_POLICY procedure
The DELETE_LOCKING_POLICY procedure deletes the password policy for all NVMe devices.
The password policy will be removed from all NVMe devices that are currently part of the policy. It will
also remove the policy itself.
Authorization: The caller must have *IOSYSCFG and *SERVICE special authorities.

Database performance and query optimization 977


DELETE_LOCKING_POLICY ( policy-password )
POLICY_PASSWORD =>

The schema is QSYS2.

policy-password A character string that contains the policy password.

Example
• Delete the password policy for all NVMe devices.

CALL QSYS2.DELETE_LOCKING_POLICY(POLICY_PASSWORD => 'My0dev9pw!');

FACTORY_RESET_DEVICE procedure
The FACTORY_RESET_DEVICE procedure resets an NVMe device to its factory settings. The device will
lose all data when this procedure is called. The PSID value printed on the physical NVMe device label is
needed to perform the reset.
Authorization: The caller must have *IOSYSCFG and *SERVICE special authorities.

FACTORY_RESET_DEVICE ( psid-password ,
PSID_PASSWORD =>

resource-name )
RESOURCE_NAME =>

The schema is QSYS2.

psid-password A character string that contains the PSID value printed on the physical device label.
resource-name A character string that contains the resource name of the device to be reset.

Example
• Reset an NVMe device back to its initial settings.

CALL QSYS2.FACTORY_RESET_DEVICE(PSID_PASSWORD => 'My0dev9pw!',


RESOURCE_NAME => 'UNIT2');

LOCKING_POLICY_INFO view
The LOCKING_POLICY_INFO view returns a list of the NVMe devices under the partition with their locking
capabilities and state.
One row is returned for each device.
Authorization: The caller must have *IOSYSCFG and *SERVICE special authorities.
The following table describes the columns in the view. The system name is LOCK_POL. The schema is
QSYS2.
Table 247. LOCKING_POLICY_INFO view

Column Name System Column Name Data Type Description

RESOURCE_NAME RESOURCE VARCHAR(10) Resource name of the NVMe device.

SERIAL_NUMBER SERIAL VARCHAR(12) Serial number of the NVMe device.

TYPE TYPE VARCHAR(4) Device type number of the NVMe device.

978 IBM i: Performance and Query Optimization


Table 247. LOCKING_POLICY_INFO view (continued)

Column Name System Column Name Data Type Description

LOCKING_SUPPORTED LOCKING VARCHAR(3) Whether this device supports locking.

NO The device does not support locking.

YES The NVMe device supports TCG Opal and has the correct
firmware allowing it to be locked.

ELIGIBLE_POLICY ELIGIBLE VARCHAR(3) Whether the device is eligible to be added to the NVMe locking
policy.

NO The device is not eligible.

YES The NVMe device is in the proper state that makes it


eligible to be added to a policy.

UNDER_POLICY IN_POLICY VARCHAR(3) Whether the device is currently under the NVMe locking policy.

NO The device is not under the policy.

YES The device is under the policy.

LOCK_STATE LOCK_STATE VARCHAR(3) Whether device is locked. When a device is locked, it is read/
write protected.

NO The device is not locked.

YES The device is not locked.

UNLOCK_ATTEMPTS_EXHAUSTED ATTEMPTS VARCHAR(3) Whether the user has exhausted their attempts to unlock the
NVMe device.

NO Additional attempts are allowed.

YES A power cycle of the NVMe decide is required before


additional attempts are allowed.

PASSWORD_FIXUP_REQUIRED FIXUP VARCHAR(3) Whether password fixup is required.

Nullable NO The NVMe device is synchronized with the password


stored in Platform KeyStore (PKS).

YES The NVMe device is not synchronized with the password


stored in PKS. The QSYS2.CHANGE_DEVICE_LOCKING
POLICY procedure with the 'FIXUP' parameter must be
run to resynchronize the values.

Returns the null value if UNDER_POLICY is NO.

Example
• List information about all NVMe devices, including whether they are eligible to be included in a locking
policy and whether a locking policy is in effect.

SELECT RESOURCE_NAME, LOCKING_SUPPORTED, ELIGIBLE_POLICY, UNDER_POLICY FROM


QSYS2.LOCKING_POLICY_INFO;

NVME_INFO view
The NVME_INFO view contains information about Non-Volatile Memory Express (NVMe) devices.
Authorization: None required.
The following table describes the columns in the view. The system name is NVME_INFO. The schema is
QSYS2.
Table 248. NVME_INFO view

Column Name System Column Name Data Type Description

DEVICE_TYPE DEV_TYPE VARCHAR(4) The type of the NVMe device.

RESOURCE_NAME RESOURCE VARCHAR(10) The resource name of the NVMe device.

Database performance and query optimization 979


Table 248. NVME_INFO view (continued)

Column Name System Column Name Data Type Description

DEVICE_MODEL DEV_MODEL VARCHAR(4) The model of the NVMe device assigned by IBM.

SERIAL_NUMBER SERIAL VARCHAR(15) The serial number of the NVMe device assigned by IBM.

HARDWARE_MODEL_NUMBER HDW_MODEL VARCHAR(40) The model number assigned by the device manufacturer.

HARDWARE_SERIAL_NUMBER HDW_SERIAL VARCHAR(20) The serial number assigned by the device manufacturer.

FIRMWARE_LEVEL FIRMWARE VARCHAR(8) The level of code running in the NVMe device.

Nullable Contains the null value if the information is not available.

IOP_NAME IOP_NAME VARCHAR(10) The name of the I/O processor.

BUS_NUMBER BUS_NUMBER INTEGER The bus number that the NVMe device is attached to.

LOCATION_CODE LOC_CODE VARCHAR(33) The location code.

PAGES_AVAILABLE PG_AVAIL BIGINT The quantity of pages on the NVMe device which remain
available to be allocated to namespaces.

PAGES_USED PG_USED BIGINT The quantity of pages on the NVMe device which have
been allocated to namespaces.

PAGES_MAXIMUM PG_MAX BIGINT The total quantity of pages which exist on the NVMe
device.

NAMESPACES_AVAILABLE NS_AVAIL INTEGER The quantity of namespaces available.

NAMESPACES_USED NS_USED INTEGER The quantity of namespaces used.

NAMESPACES_MAXIMUM NS_MAX INTEGER The maximum quantity of namespaces allowed on the


NVMe device.

NAMESPACES_CONFIGURED NS_CONFIG INTEGER The quantity of namespaces on the NVMe Device which
represent disk units that are configured into an Auxiliary
Storage Pool (ASP).

FORMAT_CRYPTO FMT_CRYPTO VARCHAR(3) NVMe device supports Format Crypto.

NO Does not support Format Crypto

YES Supports Format Crypto

OVERWRITE OVERWRITE VARCHAR(3) NVMe device supports the Overwrite sanitize operation.

NO Does not support overwrite

YES Supports overwrite

SECURE_ERASE SECURE_E VARCHAR(3) NVMe device supports the User Data Secure Erase sanitize
operation.

NO Does not support User Data Secure Erase

YES Supports User Data Secure Erase

BLOCK_ERASE BLOCK_E VARCHAR(3) NVMe device supports the Block Erase sanitize operation.

NO Does not support Block Erase

YES Supports Block Erase

CRYPTO_ERASE CRYPTO_E VARCHAR(3) NVMe device supports the Crypto Erase sanitize operation.

NO Does not support Crypto Erase

YES Supports Crypto Erase

SPARE_CAPACITY CAP_AVAIL INTEGER The percentage (0 to 100) of the remaining spare capacity
available for this NVMe device.

SPARE_CAPACITY_THRESHOLD CAP_THRESH INTEGER The threshold percentage (0 to 100) for the spare capacity
for this NVMe device.

980 IBM i: Performance and Query Optimization


Table 248. NVME_INFO view (continued)

Column Name System Column Name Data Type Description

SPARE_CAPACITY_THRESHOLD_MET CAP_MET VARCHAR(3) Whether the available spare capacity (SPARE_CAPACITY)


for the NVMe device has fallen below the threshold value
(SPARE_THRESHOLD).

NO Available spare space threshold has not been met

YES Available spare space threshold has been met

LIFE_REMAINING LIFE INTEGER The manufacturer's estimate of the percentage of the


NVMe device life remaining, based on actual usage and
the manufacturer's prediction of NVMe life.

MEMORY_BACKUP_DEVICE_FAILED BACKUPFAIL VARCHAR(3) Whether the volatile memory backup device has failed.

NO Volatile memory backup device has not failed

YES Volatile memory backup device has failed

PMR_READ_ONLY PMR_RO VARCHAR(3) Whether the persistent memory region has become read-
only.

NO Persistent memory region did not become read-


only

YES Persistent memory region became read-only

READ_ONLY DEV_RO VARCHAR(3) Whether the NVMe device is in a mode that only allows
read operations.

NO Device is not in read-only mode

YES Device is in read-only mode

DEGRADED DEGRADED VARCHAR(3) Whether the NVMe reliability has been degraded.

NO Reliability has not been degraded

YES Reliability has been degraded

TEMPERATURE_THRESHOLD HOT VARCHAR(3) Whether the temperature of the NVMe device has
exceeded the threshold.

NO Temperature threshold has not been exceeded

YES Temperature threshold has been exceeded

DATA_READ DATA_READ BIGINT The number of 512-byte data units that have been read
from the NVMe device. This value is reported in thousands
(a value of 1 corresponds to 1000 units of 512 bytes read).
This value is never reset. It is for the life of the device.

DATA_WRITTEN DATA_WRITE BIGINT The number of 512-byte data units that have been written
to the NVMe device. This value is reported in thousands (a
value of 1 corresponds to 1000 units of 512 byes written).
This value is never reset. It is for the life of the device.

HOST_READ_COMMANDS READ_CMDS BIGINT The number of read commands sent to the NVMe device
by the host system.
This value is never reset. It is for the life of the device.

HOST_WRITE_COMMANDS WRITE_CMDS BIGINT The number of write commands sent to the NVMe device
by the host system.
This value is never reset. It is for the life of the device.

CONTROLLER_BUSY_TIME BUSY_TIME BIGINT The time, in minutes, that the controller was busy
servicing I/O commands.
This value is never reset. It is for the life of the device.

POWER_CYCLES POWER_CYC BIGINT The number of times the NVMe device has been powered
on and off.
This value is never reset. It is for the life of the device.

Database performance and query optimization 981


Table 248. NVME_INFO view (continued)

Column Name System Column Name Data Type Description

POWER_ON_HOURS POWER_HOUR BIGINT The number of hours the NVMe device has been powered
on.
This value is never reset. It is for the life of the device.

UNSAFE_SHUTDOWNS POWER_LOSS BIGINT The number of times a power loss happened without a
shutdown notification being sent.
This value is never reset. It is for the life of the device.

MEDIA_ERRORS MEDIAERROR BIGINT The number of occurrences where the controller detected
an unrecovered data integrity error.
This value is never reset. It is for the life of the device.

ERROR_LOGS ERROR_LOGS BIGINT The number of error information log entries over the life of
the NVMe device.
This value is never reset. It is for the life of the device.

TEMPERATURE_WARNING_TIME TEMP_WARN INTEGER The amount of time, in minutes, that the NVMe
controller is operational and the composite temperature
is greater than or equal to the warning composite
temperature threshold and less than the critical composite
temperature.
This value is never reset. It is for the life of the device.

TEMPERATURE_CRITICAL_TIME TEMP_CRIT INTEGER The amount of time, in minutes, that the NVMe controller
is operational and the composite temperature is greater
than the critical composite temperature threshold.
This value is never reset. It is for the life of the device.

SOFT_THERMAL_TRANSITIONS SOFT_TRANS INTEGER The number of times the controller transitioned to lower
power active power states or performed manufacturer
specific thermal management actions while minimizing
the impact on performance in an attempt to reduce the
composite temperature.

HARD_THERMAL_TRANSITIONS HARD_TRANS INTEGER The number of times the controller transitioned to lower
power active power states or performed manufacturer
specific thermal management actions regardless of the
impact on performance in an attempt to reduce the
composite temperature.

SOFT_THERMAL_TIME SOFT_TIME INTEGER The number of seconds that the controller has transitioned
to lower power active power states or performed
manufacturer specific thermal management actions while
minimizing the impact on performance in order to attempt
to reduce the composite temperature.

HARD_THERMAL_TIME HARD_TIME INTEGER The number of seconds that the controller has transitioned
to lower power active power states or performed
manufacturer specific thermal management actions
regardless of the impact on performance in order to
attempt to reduce the composite temperature.

COMPOSITE_TEMPERATURE TEMP_COMP INTEGER The composite temperature (in degrees Celsius)


calculated for the device.

TEMPERATURE1 TEMP1 INTEGER The temperature (in degrees Celsius) reported by


temperature sensor 1.

TEMPERATURE2 TEMP2 INTEGER The temperature (in degrees Celsius) reported by


temperature sensor 2.

TEMPERATURE3 TEMP3 INTEGER The temperature (in degrees Celsius) reported by


temperature sensor 3.

TEMPERATURE4 TEMP4 INTEGER The temperature (in degrees Celsius) reported by


temperature sensor 4.

TEMPERATURE5 TEMP5 INTEGER The temperature (in degrees Celsius) reported by


temperature sensor 5.

TEMPERATURE6 TEMP6 INTEGER The temperature (in degrees Celsius) reported by


temperature sensor 6.

TEMPERATURE7 TEMP7 INTEGER The temperature (in degrees Celsius) reported by


temperature sensor 7

982 IBM i: Performance and Query Optimization


Table 248. NVME_INFO view (continued)

Column Name System Column Name Data Type Description

TEMPERATURE8 TEMP8 INTEGER The temperature (in degrees Celsius) reported by


temperature sensor 8.

Examples
• Return information for NVMe devices.

SELECT * FROM QSYS2.NVME_INFO;

REMOVE_DEVICE_LOCKING_POLICY procedure
The REMOVE_DEVICE_LOCKING_POLICY procedure removes an NVMe device from the password policy.
If the specified device is under the locking policy, the password will be removed from the device and the
device will no longer be under the locking policy. If the device isn’t under the locking policy, the password
will be used to remove the password from the device.
Authorization: The caller must have *IOSYSCFG and *SERVICE special authorities.

REMOVE_DEVICE_LOCKING_POLICY (
POLICY_PASSWORD =>

policy-password , resource-name )
RESOURCE_NAME =>

The schema is QSYS2.

policy-password A character string that contains the policy password.


resource-name A character string that contains the resource name of the device to be removed from
the locking policy.

Example
• Remove a device from the locking policy.

CALL QSYS2.REMOVE_DEVICE_LOCKING_POLICY(POLICY_PASSWORD => 'My0dev9pw!',


RESOURCE_NAME => 'UNIT2');

SYSDISKSTAT table function


The SYSDISKSTAT table function contains information about disks. It provides an option to reset the
baseline for collecting statistical information.
Authorization: None required.

SYSDISKSTAT ( )
reset-statistics
RESET_STATISTICS =>

The schema is QSYS2.

reset- A character or graphic string expression that contains a value of YES or NO.
statistics
If this parameter has a value of YES, statistics are reset such that the time of this query
execution is used as the new baseline. The columns that contain this statistical data have

Database performance and query optimization 983


names that are prefixed with ELAPSED_. Future invocations of SYSDISKSTAT within this
connection will return statistical detail relative to the new baseline. If this parameter has a
value of NO, statistics are not reset for the invocation. If this parameter is not specified, the
default is NO.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 249. SYSDISKSTAT table function

Column Name Data Type Description

ASP_NUMBER SMALLINT Specifies the independent auxiliary storage pool (IASP) number.

DISK_TYPE VARCHAR(4) Disk type number of the disk.

DISK_MODEL VARCHAR(4) Model number of the disk.

UNIT_NUMBER SMALLINT Unit number of the disk.

SERIAL_NUMBER VARCHAR(15) The serial number of the disk unit.

RESOURCE_NAME VARCHAR(10) The unique system-assigned name of the disk unit.

RESOURCE_STATUS VARCHAR(7) The status of the resource.

ACTIVE RESOURCE_NAME is active.

PASSIVE RESOURCE_NAME is not active.

Contains the null value if the path status is not known.

HARDWARE_STATUS VARCHAR(21) The hardware status for the disk unit.

ACTIVE The disk unit is operational and ready to accept input or


output operations.

BUSY The disk unit is being overwhelmed by a large number of


read and write operations and the disk unit is busy.

DEGRADED The disk unit is part of a disk unit subsystem that has
RAID-5 device parity protection. A decrease in performance
has occurred because a component that is not critical has
failed.

FAILED The disk unit is part of a disk unit subsystem that has device
parity protection. This unit has failed. If another unit in the
disk unit subsystem fails, data could be lost.

HARDWARE A hardware-related failure has occurred in a redundant


FAILURE component. The failure does not affect data or performance.
However, the system may become unusable if another
failure of a redundant component occurs.

NOT READY The disk unit is not ready to perform read or write
operations.

PARITY REBUILD The disk unit is part of a disk unit subsystem that has device
parity protection. The data on this unit is being rebuilt from
other units in the disk unit subsystem. If two more disk units
in the disk unit subsystem fail, data could be lost.

POWER LOSS The disk unit cannot communicate with its I/O adapter.

READ WRITE The disk unit is unable to perform read or write operations.
PROTECTED

UNKNOWN The hardware status is not known.

UNPROTECTED The disk unit is part of a disk unit subsystem that has device
parity protection. This unit is operational. However, another
unit in the disk unit subsystem has failed. If another unit in
the disk unit subsystem fails, data could be lost.

WRITE PROTECTED The disk unit is unable to perform write operations.

IS_ZERO VARCHAR(3) Indicates whether all the pages on the disk unit are zero.

NO All the pages on the disk unit are not zero.

YES All the pages on the disk unit are zero.

IOP_NAME VARCHAR(10) The name of the I/O processor.

984 IBM i: Performance and Query Optimization


Table 249. SYSDISKSTAT table function (continued)

Column Name Data Type Description

HOST_WWPN CHAR(16) A hexadecimal string representing the resource’s host world wide port name.
Contains the null value if no host world wide port name is available for this device.

REMOTE_WWPN CHAR(16) A hexadecimal string representing the resource’s remote world wide port name.
Contains the null value if no remote world wide port name is available for this device.

MULTIPLE_PATH_UNIT VARCHAR(3) A disk unit may have multiple resource names. Each resource name represents a
unique connection to the disk unit. All active connections are used to communicate
with the disk unit. This attribute indicates whether the disk unit has more than one
connection.

NO The disk unit has only one connection.

YES The disk unit has more than one connection.

UNIT_TYPE SMALLINT Indicates the type of disk unit:

0 Not solid state disk

1 Solid state disk (SSD)

UNIT_NVME SMALLINT Whether this is a Non-Volatile Memory Express (NVMe) unit.

0 Not NVMe

1 NVMe

UNIT_STORAGE_CAPACITY BIGINT Unit storage capacity has the same value as the unit media capacity for configured
disk units. This value is 0 for non-configured units.

UNIT_SPACE_AVAILABLE BIGINT Space (in bytes) available on the unit for use.

UNIT_SPACE_AVAILABLE_GB BIGINT Space, in billions of bytes, available on the unit for use.

PERCENT_USED DECIMAL(7,3) The percentage that the disk unit has been consumed.

UNIT_MEDIA_CAPACITY BIGINT Storage capacity (in bytes) of the unit.

UNIT_MEDIA_CAPACITY_GB BIGINT Storage capacity, in billions of bytes, of the unit.

STORAGE_FOR_SYSTEM BIGINT The amount of auxiliary storage on the disk unit, in millions of bytes, reserved for use
by the system.

STORAGE_ALLOCATION_ALLOWED VARCHAR(3) An indicator of whether new storage allocations are allowed on the disk unit.

NO The disk unit does not allow new storage allocations.

YES The disk unit allows new storage allocations.

PROTECTION_TYPE VARCHAR(8) The type of protection that has been assigned to this disk unit.

MIRRORED The ASP is under system mirrored protection provided by the system
software.

PARITY This disk unit is part of a parity protection array.

Contains the null value if no storage protection has been set up for this disk unit.

Database performance and query optimization 985


Table 249. SYSDISKSTAT table function (continued)

Column Name Data Type Description

PROTECTION_STATUS VARCHAR(21) The disk protection status for the disk unit, when the unit is under device parity
protection or the ASP is under mirrored protection.

ACTIVE The disk unit is active.

BUSY The disk unit is busy.

DEGRADED There is a hardware failure within the disk subsystem that


affects performance, but does not affect the function of
the disk unit.

FAILED The disk unit has failed.

HARDWARE FAILURE There is a hardware failure within the disk subsystem that
does not affect the function or performance of the disk
unit.

NOT READY The disk unit is not ready.

PARITY REBUILD The disk unit's parity protection is being rebuilt.

POWER® LOSS The disk unit is not operational.

READ WRITE The disk unit is read/write protected.


PROTECTED

RESUME The unit is part of a mirrored ASP and mirroring is in the


process of being resumed on this unit.

RESUME PENDING The unit is part of a mirrored independent ASP which is


varied off. Mirror synchronization will resume when the
independent ASP is varied on.

SUSPEND The unit is part of a mirrored ASP and mirroring is


suspended on this unit.

UNKNOWN The disk unit has returned a status that is not


recognizable by the system.

UNPROTECTED Some other disk unit in the disk subsystem has failed.

WRITE PROTECTED The disk unit is write protected.

Contains the null value if PROTECTION_TYPE is null.

RAID_TYPE VARCHAR(6) The type of RAID protection that has been assigned to this disk unit.

RAID5 This disk unit has been set up with RAID 5 protection.

RAID6 This disk unit has been set up with RAID 6 protection.

RAID10 This disk unit has been set up with RAID 10 protection.

Contains the null value if PROTECTION_TYPE is not PARITY or no storage protection


has been set up for this disk unit.

MIRRORED_SUBUNIT CHAR(1) Whether the disk unit is for subunit A or B of a mirrored pair.

Nullable A This entry is for subunit A.

B This entry is for subunit B.

Contains the null value if the unit is not a mirrored pair or if the information is not
available.

LOGICAL_MIRRORED_PAIR_ CHAR(1) Indicates the status of a mirrored pair of disks:


STATUS
0 Indicates that one mirrored unit of a mirrored pair is not active.

1 Indicates that both mirrored units of a mirrored pair are active.

Contains the null value if PROTECTION_TYPE is not MIRRORED or no storage


protection has been set up for this disk unit.

MIRRORED_UNIT_STATUS CHAR(1) Indicates the status of a mirrored unit:

1 Indicates that this mirrored unit of a mirrored pair is active (online with current
data).

2 Indicates that this mirrored unit is being synchronized.

3 Indicates that this mirrored unit is suspended.

Contains the null value if PROTECTION_TYPE is not MIRRORED.

986 IBM i: Performance and Query Optimization


Table 249. SYSDISKSTAT table function (continued)

Column Name Data Type Description

AVAILABILITY_PARITY_SET_UNIT VARCHAR(3) Whether the disk unit is in an availability parity set.

NO The disk unit is not in an availability parity set.

YES The disk unit is in an availability parity set.

HYPERSWAP VARCHAR(3) Whether unit is using HyperSwap®.

NO Unit is not using HyperSwap.

YES Unit is using HyperSwap.

FIRMWARE_LEVEL VARCHAR(8) The level of code running in the SSD device.

Nullable Contains the null value if this disk is not a mainstream SSD or if the information
is not available. See Mainstream solid-state drives for a description of mainstream
solid-state drives.

SSD_PART_NUMBER VARCHAR(12) The part number as reported by the SSD device.

Nullable Contains the null value if this disk is not a mainstream SSD or if the information is not
available.

SSD_POWER_ON_DAYS BIGINT The number of days that the SSD device has been active in a system.

Nullable Contains the null value if this disk is not a mainstream SSD or if the information is not
available.

SSD_LIFE_REMAINING INTEGER The percentage of the lifetime remaining for the SSD device. This estimates the
percentage of usable function remaining for the drive before it should be replaced.
Nullable Calculations for this percentage include more than just the number of bytes written
and supported.
Contains the null value if this disk is not a mainstream SSD or if the information is not
available.

SSD_READ_WRITE_PROTECTED VARCHAR(3) Whether the device is read/write protected.

Nullable NO The SSD device is not read/write protected

YES The SSD device is read/write protected

Contains the null value if this disk is not a mainstream SSD or if the information is not
available.

SSD_BYTES_WRITTEN DECIMAL(20,0) The lifetime number of bytes, in gigabytes, that have been physically written to the
NAND memory in this particular SSD disk unit. This is strongly related to bytes written
Nullable by the applications using the drive, but will not match.
Contains the null value if this disk is not a mainstream SSD or if the information is not
available.

SSD_SUPPORTED_BYTES_WRITTEN DECIMAL(20,0) The lifetime number of bytes, in gigabytes, that the SSD is expected to be able to
physically write at a minimum. Additional writes beyond this number may start to fail
Nullable due to the limited write endurance of a Read Intensive drive.
Contains the null value if this disk is not a mainstream SSD or if the information is not
available.

SSD_PFA_WARNING VARCHAR(3) Whether the Predictive Failure Analysis warning has been logged.

Nullable NO The Predictive Failure Analysis warning has not been logged.

YES The Predictive Failure Analysis warning has been logged.

Contains the null value if this disk is not a mainstream SSD or if the information is not
available.

TOTAL_SAMPLE_COUNT BIGINT The number of times the disk queue was checked to determine whether or not the
queue is empty.

TOTAL_NOT_BUSY_COUNT BIGINT The number of times the disk queue was empty during the same time period
that the sample count was taken. The busy count can be calculated as
TOTAL_SAMPLE_COUNT - TOTAL_NOT_BUSY_COUNT.

TOTAL_READ_REQUESTS BIGINT The number of input data transfer requests processed for the disk unit since the last
IPL. This value is not directly related to the number of blocks transferred for the disk
unit because the number of blocks to be transferred for a given transfer request can
vary greatly. This value will wrap back to 1 when 2,147,483,647 is reached.

Database performance and query optimization 987


Table 249. SYSDISKSTAT table function (continued)

Column Name Data Type Description

TOTAL_WRITE_REQUESTS BIGINT The number of output data transfer requests processed for the disk unit since the last
IPL. This value is not directly related to the number of blocks transferred for the disk
unit because the number of blocks to be transferred for a given transfer request can
vary greatly. This value will wrap back to 1 when 2,147,483,647 is reached.

TOTAL_BLOCKS_READ BIGINT The number of 512-byte blocks transferred from the disk unit since the last IPL. This
value will wrap back to 1 when 2,147,483,647 is reached.

TOTAL_BLOCKS_WRITTEN BIGINT The number of 512-byte blocks transferred to the disk unit since the last IPL. This
value will wrap back to 1 when 2,147,483,647 is reached.

TOTAL_PERMANENT_BLOCKS_WRITTE BIGINT The number of 512-byte blocks of permanent storage transferred to the disk unit
N since the last IPL. This value will wrap back to 1 when 2,147,483,647 is reached.

TOTAL_PERMANENT_WRITE_REQUEST BIGINT The number of output permanent data transfer requests processed for the disk
S unit since the last IPL. This value is not directly related to the permanent blocks
transferred from main storage for the disk unit because the number of blocks
transferred for a given transfer request can vary greatly. This value will wrap back
to 1 when 2,147,483,647 is reached.

ELAPSED_TIME INTEGER The time that has elapsed, in seconds, between the measurement start time and the
current system time.

ELAPSED_IO_REQUESTS DECIMAL(6,1) The average number of I/O requests for read and write operations that occurred per
second during the elapsed time.

ELAPSED_REQUEST_SIZE DECIMAL(6,1) The average size of an I/O request in KB during the elapsed time.

ELAPSED_READ_REQUESTS DECIMAL(6,1) The average number of requests per second to transfer data from the disk unit during
the elapsed time.

ELAPSED_WRITE_REQUESTS DECIMAL(6,1) The average number of requests per second to transfer data to the disk unit during
the elapsed time.

ELAPSED_DATA_READ DECIMAL(6,1) The average amount of data, in KB, transferred from the disk unit, per request, during
the elapsed time.

ELAPSED_DATA_WRITTEN DECIMAL(6,1) The average amount of data, in KB, transferred to the disk unit, per request, during
the elapsed time.

ELAPSED_PERCENT_BUSY DECIMAL(4,1) The estimated percentage of time the disk unit is being used during the elapsed time.

Example
• Return information about all disks, resetting the statistical information shown for the current job.

SELECT * FROM TABLE(QSYS2.SYSDISKSTAT(RESET_STATISTICS=>'YES'));

SYSDISKSTAT view
The SYSDISKSTAT view contains information about spinning disk and solid-state drives (SSD).
The information returned is similar to the detail seen from the Work with Disk Status (WRKDSKSTS)
command and from the Open List of ASPs (QYASPOL) API.
The view contains one or more rows for every disk unit on the system, including non-configured
(unallocated) disk units. For non-configured units, the UNIT_NUMBER is 0. For a disk which has multiple
paths to the disk unit, there will be a row for each unique path to the disk unit. For such disks, the
MULTIPLE_PATH_UNIT column will be YES and each RESOURCE_NAME column will identify a different
path to the disk unit.
Authorization: None required.
The following table describes the columns in the view. The system name is SYSDISKS. The schema is
QSYS2.
Table 250. SYSDISKSTAT view

Column Name System Column Name Data Type Description

ASP_NUMBER ASP_NUMBER SMALLINT Specifies the storage pool (ASP) number.

988 IBM i: Performance and Query Optimization


Table 250. SYSDISKSTAT view (continued)

Column Name System Column Name Data Type Description

DISK_TYPE DISK_TYPE VARCHAR(4) Disk type number of the disk.

DISK_MODEL DISK_MODEL VARCHAR(4) Model number of the disk.

UNIT_NUMBER UNITNBR SMALLINT Unit number of the disk.

SERIAL_NUMBER SERIALNBR VARCHAR(15) The serial number of the disk unit.

RESOURCE_NAME RESOURCE VARCHAR(10) The unique system-assigned name of the disk unit.

RESOURCE_STATUS PATHSTATUS VARCHAR(7) The status of the resource.

Nullable ACTIVE RESOURCE_NAME is active.

PASSIVE RESOURCE_NAME is not active.

Contains the null value if the path status is not known.

HARDWARE_STATUS HDW_STATUS VARCHAR(21) The hardware status for the disk unit.

ACTIVE The disk unit is operational and


ready to accept input or output
operations.

BUSY The disk unit is being overwhelmed


by a large number of read and write
operations and the disk unit is busy.

DEGRADED The disk unit is part of a disk unit


subsystem that has RAID-5 device
parity protection. A decrease in
performance has occurred because
a component that is not critical has
failed.

FAILED The disk unit is part of a disk unit


subsystem that has device parity
protection. This unit has failed.
If another unit in the disk unit
subsystem fails, data could be lost.

HARDWARE A hardware-related failure has


FAILURE occurred in a redundant component.
The failure does not affect data or
performance. However, the system
may become unusable if another
failure of a redundant component
occurs.

NOT READY The disk unit is not ready to perform


read or write operations.

PARITY REBUILD The disk unit is part of a disk unit


subsystem that has device parity
protection. The data on this unit is
being rebuilt from other units in the
disk unit subsystem. If two more
disk units in the disk unit subsystem
fail, data could be lost.

POWER LOSS The disk unit cannot communicate


with its I/O adapter.

READ WRITE The disk unit is unable to perform


PROTECTED read or write operations.

UNKNOWN The hardware status is not known.

UNPROTECTED The disk unit is part of a disk unit


subsystem that has device parity
protection. This unit is operational.
However, another unit in the disk
unit subsystem has failed. If another
unit in the disk unit subsystem fails,
data could be lost.

WRITE The disk unit is unable to perform


PROTECTED write operations.

Database performance and query optimization 989


Table 250. SYSDISKSTAT view (continued)

Column Name System Column Name Data Type Description

IS_ZERO IS_ZERO VARCHAR(3) Indicates whether all the pages on the disk unit are zero.

NO All the pages on the disk unit are not zero.

YES All the pages on the disk unit are zero.

IOP_NAME IOP_NAME VARCHAR(10) The name of the I/O processor.

HOST_WWPN HOST_WWPN CHAR(16) A hexadecimal string representing the resource’s host


world wide port name.
Contains the null value if no host world wide port name is
available for this device.

REMOTE_WWPN RMT_WWPN CHAR(16) A hexadecimal string representing the resource’s remote


world wide port name.
Contains the null value if no remote world wide port name
is available for this device.

MULTIPLE_PATH_UNIT MULTI_PATH VARCHAR(3) A disk unit may have multiple resource names. Each
resource name represents a unique connection to the disk
unit. All active connections are used to communicate with
the disk unit. This attribute indicates whether the disk unit
has more than one connection.

NO The disk unit has only one connection.

YES The disk unit has more than one connection.

UNIT_TYPE UNIT_TYPE SMALLINT Indicates the type of disk unit:

0 Not solid state disk

1 Solid state disk (SSD)

UNIT_NVME UNIT_NVME SMALLINT Whether this is a Non-Volatile Memory Express (NVMe)


unit.

0 Not NVMe

1 NVMe

UNIT_STORAGE_CAPACITY UNITSCAP BIGINT Unit storage capacity has the same value as the unit media
capacity for configured disk units. This value is 0 for non-
configured units.

UNIT_SPACE_AVAILABLE UNITSPACE BIGINT Space (in bytes) available on the unit for use.

UNIT_SPACE_AVAILABLE_GB UNITSPCGB BIGINT Space, in billions of bytes, available on the unit for use.

PERCENT_USED PERCENTUSE DECIMAL(7,3) The percentage that the disk unit has been consumed.
Nullable

UNIT_MEDIA_CAPACITY UNITMCAP BIGINT Storage capacity (in bytes) of the unit.

UNIT_MEDIA_CAPACITY_GB UNITMCAPGB BIGINT Storage capacity, in billions of bytes, of the unit.

STORAGE_FOR_SYSTEM STORAGESYS BIGINT The amount of auxiliary storage on the disk unit, in millions
of bytes, reserved for use by the system.

STORAGE_ALLOCATION_ALLOWED NEW_ALLOC VARCHAR(3) An indicator of whether new storage allocations are


allowed on the disk unit.

NO The disk unit does not allow new storage


allocations.

YES The disk unit allows new storage allocations.

990 IBM i: Performance and Query Optimization


Table 250. SYSDISKSTAT view (continued)

Column Name System Column Name Data Type Description

PROTECTION_TYPE PROTECTION VARCHAR(8) The type of protection that has been assigned to this disk
unit.
Nullable
MIRRORED The ASP is under system mirrored
protection provided by the system
software.

PARITY This disk unit is part of a parity protection


array.

Contains the null value if no storage protection has been


set up for this disk unit.

PROTECTION_STATUS STATUS VARCHAR(21) The disk protection status for the disk unit, when the
unit is under device parity protection or the ASP is under
Nullable mirrored protection.

ACTIVE The disk unit is active.

BUSY The disk unit is busy.

DEGRADED There is a hardware failure within


the disk subsystem that affects
performance, but does not affect
the function of the disk unit.

FAILED The disk unit has failed.

HARDWARE There is a hardware failure within


FAILURE the disk subsystem that does not
affect the function or performance
of the disk unit.

NOT READY The disk unit is not ready.

PARITY REBUILD The disk unit's parity protection is


being rebuilt.

POWER LOSS The disk unit is not operational.

READ WRITE The disk unit is read/write


PROTECTED protected.

RESUME The unit is part of a mirrored ASP


and mirroring is in the process of
being resumed on this unit.

RESUME The unit is part of a mirrored


PENDING independent ASP which is varied
off. Mirror synchronization will
resume when the independent ASP
is varied on.

SUSPEND The unit is part of a mirrored ASP


and mirroring is suspended on this
unit.

UNKNOWN The disk unit has returned a status


that is not recognizable by the
system.

UNPROTECTED Some other disk unit in the disk


subsystem has failed.

WRITE The disk unit is write protected.


PROTECTED

Contains the null value if PROTECTION_TYPE is null.

Database performance and query optimization 991


Table 250. SYSDISKSTAT view (continued)

Column Name System Column Name Data Type Description

RAID_TYPE RAID_TYPE VARCHAR(6) The type of RAID protection that has been assigned to this
disk unit.
Nullable
RAID5 This disk unit has been set up with RAID 5
protection.

RAID6 This disk unit has been set up with RAID 6


protection.

RAID10 This disk unit has been set up with RAID 10


protection.

Contains the null value if PROTECTION_TYPE is not


PARITY or no storage protection has been set up for this
disk unit.

MIRRORED_SUBUNIT SUBUNIT CHAR(1) Whether the disk unit is for subunit A or B of a mirrored
pair.
Nullable
A This entry is for subunit A.

B This entry is for subunit B.

Contains the null value if the unit is not a mirrored pair or if


the information is not available.

LOGICAL_MIRRORED_PAIR_ MIRRORPS CHAR(1) Indicates the status of a mirrored pair of disks:


STATUS Nullable
0 Indicates that one mirrored unit of a mirrored pair is
not active.

1 Indicates that both mirrored units of a mirrored pair


are active.

Contains the null value if PROTECTION_TYPE is not


MIRRORED or no storage protection has been set up for
this disk unit.

MIRRORED_UNIT_STATUS MIRRORUS CHAR(1) Indicates the status of a mirrored unit:


Nullable
1 Indicates that this mirrored unit of a mirrored pair is
active (online with current data).

2 Indicates that this mirrored unit is being


synchronized.

3 Indicates that this mirrored unit is suspended.

Contains the null value if PROTECTION_TYPE is not


MIRRORED.

AVAILABILITY_PARITY_SET_UNIT PARITY VARCHAR(3) Whether the disk unit is in a parity set which is optimized
for availability.

NO The disk unit is not in an availability parity set.

YES The disk unit is in an availability parity set.

HYPERSWAP HYPERSWAP VARCHAR(3) Whether unit is using HyperSwap.

NO Unit is not using HyperSwap.

YES Unit is using HyperSwap.

FIRMWARE_LEVEL FIRMWARE VARCHAR(8) The level of code running in the SSD device.

Nullable Contains the null value if this disk is not a mainstream SSD
or if the information is not available. See Mainstream solid-
state drives for a description of mainstream solid-state
drives.

SSD_PART_NUMBER SSD_PART VARCHAR(12) The part number as reported by the SSD device.

Nullable Contains the null value if this disk is not a mainstream SSD
or if the information is not available.

SSD_POWER_ON_DAYS SSD_DAYS BIGINT The number of days that the SSD device has been active in
a system.
Nullable
Contains the null value if this disk is not a mainstream SSD
or if the information is not available.

992 IBM i: Performance and Query Optimization


Table 250. SYSDISKSTAT view (continued)

Column Name System Column Name Data Type Description

SSD_LIFE_REMAINING SSD_LIFE INTEGER The percentage of the lifetime remaining for the SSD
device. This estimates the percentage of usable function
Nullable remaining for the drive before it should be replaced.
Calculations for this percentage include more than just the
number of bytes written and supported.
Contains the null value if this disk is not a mainstream SSD
or if the information is not available.

SSD_READ_WRITE_PROTECTED SSD_PROT VARCHAR(3) Whether the device is read/write protected.

Nullable NO The SSD device is not read/write protected

YES The SSD device is read/write protected

Contains the null value if this disk is not a mainstream SSD


or if the information is not available.

SSD_BYTES_WRITTEN SSD_WRITE DECIMAL(20,0) The lifetime number of bytes, in gigabytes, that have been
physically written to the NAND memory in this particular
Nullable SSD disk unit. This is strongly related to bytes written by
the applications using the drive, but will not match.
Contains the null value if this disk is not a mainstream SSD
or if the information is not available.

SSD_SUPPORTED_BYTES_WRITTEN SSD_MAX_W DECIMAL(20,0) The lifetime number of bytes, in gigabytes, that the SSD
is expected to be able to physically write at a minimum.
Nullable Additional writes beyond this number may start to fail due
to the limited write endurance of a Read Intensive drive.
Contains the null value if this disk is not a mainstream SSD
or if the information is not available.

SSD_PFA_WARNING SSD_PFA VARCHAR(3) Whether the Predictive Failure Analysis warning has been
logged.
Nullable
NO The Predictive Failure Analysis warning has not
been logged.

YES The Predictive Failure Analysis warning has been


logged.

Contains the null value if this disk is not a mainstream SSD


or if the information is not available.

TOTAL_SAMPLE_COUNT SAMPLED BIGINT The number of times the disk queue was checked to
determine whether or not the queue is empty.

TOTAL_NOT_BUSY_COUNT NOT_BUSY BIGINT The number of times the disk queue was empty during the
same time period that the sample count was taken. The
busy count can be calculated as TOTAL_SAMPLE_COUNT -
TOTAL_NOT_BUSY_COUNT.

TOTAL_READ_REQUESTS REQ_IN BIGINT The number of input data transfer requests processed for
the disk unit since the last IPL. This value is not directly
related to the number of blocks transferred for the disk
unit because the number of blocks to be transferred for
a given transfer request can vary greatly. This value will
wrap back to 1 when 2,147,483,647 is reached.

TOTAL_WRITE_REQUESTS REQ_OUT BIGINT The number of output data transfer requests processed for
the disk unit since the last IPL. This value is not directly
related to the number of blocks transferred for the disk
unit because the number of blocks to be transferred for
a given transfer request can vary greatly. This value will
wrap back to 1 when 2,147,483,647 is reached.

TOTAL_BLOCKS_READ BLOCK_IN BIGINT The number of 512-byte blocks transferred from the disk
unit since the last IPL. This value will wrap back to 1 when
2,147,483,647 is reached.

TOTAL_BLOCKS_WRITTEN BLOCK_OUT BIGINT The number of 512-byte blocks transferred to the disk unit
since the last IPL. This value will wrap back to 1 when
2,147,483,647 is reached.

TOTAL_PERMANENT_BLOCKS_WRITTEN BLOCK_PERM BIGINT The number of 512-byte blocks of permanent storage


transferred to the disk unit since the last IPL. This value
will wrap back to 1 when 2,147,483,647 is reached.

Database performance and query optimization 993


Table 250. SYSDISKSTAT view (continued)

Column Name System Column Name Data Type Description

TOTAL_PERMANENT_WRITE_REQUESTS REQ_PERM BIGINT The number of output permanent data transfer requests
processed for the disk unit since the last IPL. This
value is not directly related to the permanent blocks
transferred from main storage for the disk unit because
the number of blocks transferred for a given transfer
request can vary greatly. This value will wrap back to 1
when 2,147,483,647 is reached.

ELAPSED_TIME ELAP_TIME INTEGER The time that has elapsed, in seconds, between the
measurement start time and the current system time.

ELAPSED_IO_REQUESTS ELAP_IO DECIMAL(6,1) The average number of I/O requests for read and write
operations that occurred per second during the elapsed
Nullable time.

ELAPSED_REQUEST_SIZE ELAP_SIZE DECIMAL(6,1) The average size of an I/O request in KB during the
elapsed time.
Nullable

ELAPSED_READ_REQUESTS ELAP_REQ_R DECIMAL(6,1) The average number of requests per second to transfer
data from the disk unit during the elapsed time.
Nullable

ELAPSED_WRITE_REQUESTS ELAP_REQ_W DECIMAL(6,1) The average number of requests per second to transfer
data to the disk unit during the elapsed time.
Nullable

ELAPSED_DATA_READ ELAP_DTA_R DECIMAL(6,1) The average amount of data, in KB, transferred from the
disk unit, per request, during the elapsed time.
Nullable

ELAPSED_DATA_WRITTEN ELAP_DTA_W DECIMAL(6,1) The average amount of data, in KB, transferred to the disk
unit, per request, during the elapsed time.
Nullable

ELAPSED_PERCENT_BUSY ELAP_BUSY DECIMAL(4,1) The estimated percentage of time the disk unit is being
used during the elapsed time.
Nullable

Notes
The values in the ELAPSED_ columns are based on the TOTAL_ columns. When an ELAPSED calculation
notices that the ending value is less than the value at the start of the time interval, it adds 2,147,483,647
to the ending value for an accurate result. When this happens, a warning SQLSTATE '01687' is issued.
It is recommended that the statistics get reset using the QSYS2.SYSDISKSTAT table function before the
counters can wrap more than once. The frequency needed for this action depends on the size and activity
of the disk units.
The ELAPSED_ column information is derived from the values reported in the TOTAL_ columns as shown
in the following table. These formulas can be used to calculate identical statistics if you want to save
historical disk statistics in a permanent table.
For clarity, the values prefixed by delta_ indicate the difference between two rows in the corresponding
TOTAL_ columns. For example, delta_READ_REQUESTS means TOTAL_READ_REQUESTS(time2) -
TOTAL_READ_REQUESTS(time1). The delta_time value means the time in seconds between time1 and
time2.

Table 251. Calculating elapsed data


Elapsed column name TOTAL_ columns used to calculate the Notes
elapsed value
ELAPSED_IO_REQUESTS (delta_READ_REQUESTS +
delta_WRITE_REQUESTS) / delta_time
ELAPSED_REQUEST_SIZE ((delta_BLOCKS_READ + Divide by 2 to convert
delta_BLOCKS_WRITTEN) / 2) value from 512 byte
(delta_READ_REQUESTS + blocks to KB.
delta_WRITE_REQUESTS)

994 IBM i: Performance and Query Optimization


Table 251. Calculating elapsed data (continued)
Elapsed column name TOTAL_ columns used to calculate the Notes
elapsed value
ELAPSED_READ_REQUESTS delta_READ_REQUESTS / delta_time
ELAPSED_WRITE_REQUESTS delta_WRITE_REQUESTS / delta_time
ELAPSED_DATA_READ (delta_BLOCKS_READ / 2) / Divide by 2 to convert
delta_READ_REQUESTS value from 512 byte
blocks to KB.
ELAPSED_DATA_WRITTEN (delta_BLOCKS_WRITTEN / 2) / Divide by 2 to convert
delta_WRITE_REQUESTS value from 512 byte
blocks to KB.
ELAPSED_PERCENT_BUSY ((delta_SAMPLE_COUNT -
delta_NOT_BUSY_COUNT) /
delta_SAMPLE_COUNT) * 100

Examples
• Return information about all disks.

SELECT * FROM QSYS2.SYSDISKSTAT

• Return information for all SSD units.

SELECT * FROM QSYS2.SYSDISKSTAT WHERE UNIT_TYPE = 1

SYSTMPSTG view
The SYSTMPSTG view contains one row for every temporary storage bucket that is tracking some amount
of temporary storage across the system.
Temporary storage is application working storage that does not persist across a restart of the operating
system. Accounting for all the temporary storage being used on the system is implemented using the
concept of temporary storage buckets.
There are two types of temporary storage buckets:
• global buckets that are used to track temporary storage that is scoped to all jobs on the system.
• job buckets that are used to track temporary storage that is scoped to a single job.
Each bucket has a bucket number. Global buckets managed by the licensed internal code have bucket
numbers from 1 to 4095. Global buckets managed by IBM i Work Management have bucket numbers from
4096 to 65535. Job buckets have numbers greater than 65535.
A job temporary storage bucket is assigned when the job starts and does not change for the life of the
job. A job temporary storage bucket will normally be empty after the associated job ends and all working
storage for the job is deleted or freed. If the job temporary storage bucket is empty after the job ends,
the bucket becomes available to be associated with a new job. If the job associated with the job buckets
ends and some temporary objects tracked to that job are not deleted, the job bucket will show a status
of *ENDED as well as the date and time that the job ended. These job buckets identify jobs that are not
deleting all of their temporary storage when the job ends.
Statistics for each job bucket indicate the current amount of storage (in bytes) used for temporary storage
tracked by the bucket, the storage limit (in bytes) for storage used for temporary storage tracked by the
bucket, and the peak amount of storage (in bytes) used for temporary storage tracked by the bucket. A job
bucket does not include any temporary storage used for SQL query execution. For job buckets, the storage
limit will reflect the MAXTMPSTG value of the class (*CLS) object specified when the job was submitted; a
null value is returned if the job has a MAXTMPSTG value of *NOMAX.

Database performance and query optimization 995


Authorization: None required.
The following table describes the columns in the view. The schema is QSYS2.
Table 252. SYSTMPSTG view

Column Name System Column Name Data Type Description

BUCKET_NUMBER BKTNBR INTEGER Number that uniquely identifies the temporary storage bucket.

GLOBAL_BUCKET_NAME GLBBKTNAME VARCHAR(30) For global buckets, the name of the bucket.
Nullable For job buckets, contains the null value.

JOBNAME JOBNAME VARCHAR(10) For job buckets, the job name.


Nullable For global buckets, contains the null value.

JOB_USER_NAME JOBUSRNAME VARCHAR(10) For job buckets, the user profile under which the job is run.
Nullable For global buckets, contains the null value.

JOB_NUMBER JOBNBR CHAR(6) For job buckets, the job number assigned by the system.
Nullable For global buckets, contains the null value.

BUCKET_CURRENT_SIZE BKTCURSIZ DECIMAL(23,0) The current number of bytes of storage for this temporary
storage bucket.

BUCKET_LIMIT_SIZE BKTLMTSIZ DECIMAL(23,0) The current limit, in bytes, for the amount of storage for this
Nullable temporary storage bucket. If the temporary storage bucket has
no limit, contains the null value.

BUCKET_PEAK_SIZE BKTPEAKSIZ DECIMAL(23,0) The largest number of bytes of storage for this temporary storage
bucket. For global buckets, this is the peak amount of storage
since the last restart of the operating system. For job buckets,
this is the peak amount of storage since the job was started.

JOB_STATUS JOBSTS VARCHAR(7) For job buckets, indicates whether the bucket is associated with
Nullable an active job or a job that ended without deleting all temporary
objects associated with the job.

*ENDED The job associated with this job bucket has ended.

*ACTIVE The job associated with this job bucket is still


active.

For global buckets, contains the null value.

JOB_ENDED_TIME JOBENDTIM TIMESTAMP For job buckets associated with jobs that have ended, indicates
Nullable the timestamp of when the associated job ended.
Contains the null value for global buckets and job buckets
associated with active jobs.

UNLOCK_DEVICE procedure
The UNLOCK_DEVICE procedure attempts to unlock an NVMe device.
Authorization: The caller must have *IOSYSCFG and *SERVICE special authorities.

UNLOCK_DEVICE ( policy-password ,
POLICY_PASSWORD =>

resource-name )
RESOURCE_NAME =>

The schema is QSYS2.

policy-password A character string that contains the policy password.


resource-name A character string that contains the resource name of the device to be unlocked.

Example
• Unlock an NVMe device.

996 IBM i: Performance and Query Optimization


CALL QSYS2.UNLOCK_DEVICE(POLICY_PASSWORD => 'My0dev9pw!',
RESOURCE_NAME => 'UNIT2');

USER_STORAGE view
The USER_STORAGE view contains details about storage by user profile.
The user storage consumption detail is determined by using Retrieve User Information (QSYRUSRI) API.
You must have *OBJOPR and *READ authority to a *USRPRF or it will not be returned. To see information
for independent ASPs (iASPs), the iASP must be varied on.
User storage is broken down by SYSBAS and iASPs.
Authorization: The caller must have *OBJOPR and *READ authorities to the *USRPRF.
The following table describes the columns in the view. The system name is USER_STG. The schema is
QSYS2.
Table 253. USER_STORAGE view

Column Name System Column Name Data Type Description

AUTHORIZATION_NAME USER_NAME VARCHAR(10) User profile name.

Nullable

ASPGRP ASPGRP VARCHAR(10) Name of the independent ASP or *SYSBAS.

Nullable

MAXIMUM_STORAGE_ALLOWED MAXSTG BIGINT The maximum amount of auxiliary storage (in kilobytes) that
can be assigned to store permanent objects owned by the user.
Nullable Contains null if the user does not have a maximum amount of
allowed storage.

STORAGE_USED STGUSED BIGINT The amount of auxiliary storage (in kilobytes) occupied by the
user's owned objects for this ASPGRP.
Nullable

Example
Determine how much storage user SCOTTF has consumed.

SELECT * FROM QSYS2.USER_STORAGE


WHERE USER_NAME = 'SCOTTF'

System Health Services


For the most important system resources, the IBM i operating system automatically tracks the highest
consumption and consumers.
The IBM i operating system is comprised of many products and components. As an integrated operating
system, not only do the products and components frequently rely upon each other, but common building
blocks and resources are used. Some of the resources are deemed to be critical because their proper use
and consumption is directly related to achieving continued, normal operational behavior. The repository
for this tracking lies within Db2 for i.
A table, a view, and global variables combine to provide information about limits on your system.
Information about the important limits is logged in a Db2 for i supplied table named QSYS2.SYSLIMTBL.
The QSYS2.SYSLIMITS view uses SYSLIMTBL and other Db2 resources to provide extended and formatted
detail about these limits. You should generally work with the view rather than the underlying table. You
can use Db2 for i provided global variables to control the number of rows kept for each type of limit in
SYSLIMTBL.
The following tables list the limits that are tracked along with the corresponding limit ID, the system
maximum value, the value that will cause the first row to be added to SYSLIMTBL (the floor), and the

Database performance and query optimization 997


amount of change after this first row is written that causes subsequent rows to be added to the table (the
increment).

Table 254. Database limits


Limit
Limit description ID Maximum Floor Increment
Maximum number of all rows 15000 4,294,967,288 100,000 500,000
in a partition
Maximum number of valid 15001 4,294,967,288 100,000 500,000
rows in a partition
Maximum number of deleted 15002 4,294,967,288 10,000 100,000
rows in a partition
Maximum size of a table 15003 1,869,169,767,219 536,865,792 1,073,731,584
Maximum number of 15004 4,294,967,288 10,000 100,000
overflow rows in a partition
Maximum number of 15104 65,533 100 100
variable-length segments
Maximum number of indexes 15106 15,000 20 100
over a partition
Maximum size of a *MAX4GB 15400 4,294,967,296 838,860,800 167,772,160
index
Maximum size of a *MAX1TB 15401 1,869,166,411,776 8,388,608,000 8,388,608,000
index
Maximum size of an encoded 15403 2,199,023,255,552 1,677,721,600 8,388,608,000
vector index
Maximum number of 16100 32,767 100 50
members in a source
physical file
Maximum number of rows 16200 500,000,000 10,000 100,000
locked in a unit of work
Maximum number of row 16201 storage 10,000 100,000
change operations in a unit
of work
Maximum size of an 16806 1,056,964,608 335,544,320 8,388,608
extended dynamic package

Table 255. Journal limits


Limit
Limit description ID Maximum Floor Increment
Maximum size of a journal 18300 1,099,511,627,776 10,000,000,000 50,000,000,000
receiver
Maximum number of objects 18301 10,000,000 10,000 200,000
that can be associated with a
*MAX10M journal

998 IBM i: Performance and Query Optimization


Table 255. Journal limits (continued)
Limit
Limit description ID Maximum Floor Increment
Maximum number of objects 18302 250,000 10,000 50,000
that can be associated with a
*MAX250K journal
Maximum sequence number 18303 10,000,000 100,000,000
18,446,744,073
of a *MAXOPT3 journal ,709,551,600

Maximum sequence number 18304 9,999,999,999 10,000,000 10,000,000


of a *MAXOPT1 or *MAXOPT2
journal

Table 256. File system limits


Limit
Limit description ID Maximum Floor Increment
Maximum number of object 18400 1,000,000 1,000 1,000
description entries in a
library
Number of objects linked in a 18402 storage 100,000 10,000
directory
Maximum number of 18403 1,000,000 1,000 1,000
directories linked in a
directory
Maximum number of file 18404 2,147,483,647 100,000 10,000
system objects in *SYSBAS
ASPs
Maximum number of file 18405 2,147,483,647 100,000 10,000
system objects in an
independent ASP
Maximum number of 18406 65510 1,000 500
document library objects in a
folder
Number of document library 18407 storage 100,000 10,000
objects in the system ASP
Maximum number of 18408 1,000,000 100,000 10,000
document library objects in a
user ASP
Maximum number of bytes in 18409 1,099,511,627,776 16,777,216 1,048,576
a stream file
Maximum number of bytes in 18410 2,147,483,647 16,777,216 1,048,576
a document

Database performance and query optimization 999


Table 257. Work management limits
Limit
Limit description ID Maximum Floor Increment
Maximum number of jobs 19000 970,000 1,000 400
Maximum number of spool 19002 2,610,000 10,000 5,000
files
Maximum number of spooled 19003 10,000,000 10,000 5,000
files in each independent
ASP

System limit alerts


Some system limits are instrumented by the IBM i operating system to send messages to the QSYSOPR
message queue when a threshold value has been reached.
Once each day, the IBM i will look for any limits that have surpassed their alerting level. This happens
when Collection Services is recycled, typically just past midnight. At this time, a call is made to the
QSYS2.PROCESS_SYSTEM_LIMITS_ALERTS procedure to identify and signal any alerts for the day.
The following limits are checked against their alerting level as part of this daily processing. If the level
is exceeded, a severity 80 informational message SQL7062 is sent to the QSYSOPR message queue.
Since these limits will prevent database or other system activity from continuing if they are reached, you
should take action to get the object's percent used for the limit below the alerting level. Reducing data by
archiving it is one example of an action that could be taken.

Table 258. System limits that send alerting messages


Limit ID Limit description Maximum Default Alerting Alerting Cadence
Level
15000 Maximum number 4,294,967,288 Greater than 90% Once per day
of all rows in a
partition
15002 Maximum number of 4,294,967,288 Greater than 50% Once per day
deleted rows in a
partition
15003 Maximum size of a 1,869,169,767,219 Greater than 90% Once per day
table
15104 Maximum number 65,533 Greater than 90% Once per day
of variable-length
segments
15400 Maximum *MAX4GB 4,294,967,296 Greater than 90% Once per day
Index Size
15401 Maximum *MAX1TB 1,869,166,411,776 Greater than 90% Once per day
Index Size
15403 Maximum Encoded 2,199,023,255,552 Greater than 90% Once per day
Vector Index Size
19002 Maximum number of 2,610,000 Greater than 90% Once per day
spooled files

The SQL7062 QSYSOPR message is formatted like this:

1000 IBM i: Performance and Query Optimization


MYLIB/MYTABLE *FILE HAS CONSUMED MORE THAN 90% OF THE LIMIT:
15000-MAXIMUM NUMBER OF ALL ROWS (4008420999 OF 4294967288=93.33%).
REFER TO ibm.biz/DB2foriAlerts FOR MORE DETAIL.

System limit alerts global variables


For each limit that is instrumented to send a system limit alert, a corresponding global variable is defined
that can be used to modify the consumption level that causes the alert to be issued.
The following are the names of the global variables. The schema is SYSIBMADM.

Limit ID Global variable Shipped limit


15000 QIBM_SYSTEM_LIMITS_ALERT_15000_PERCENTAGE 90
15002 QIBM_SYSTEM_LIMITS_ALERT_15002_PERCENTAGE 50
15003 QIBM_SYSTEM_LIMITS_ALERT_15003_PERCENTAGE 90
15104 QIBM_SYSTEM_LIMITS_ALERT_15104_PERCENTAGE 90
15400 QIBM_SYSTEM_LIMITS_ALERT_15400_PERCENTAGE 90
15401 QIBM_SYSTEM_LIMITS_ALERT_15401_PERCENTAGE 90
15403 QIBM_SYSTEM_LIMITS_ALERT_15403_PERCENTAGE 90
19002 QIBM_SYSTEM_LIMITS_ALERT_19002_PERCENTAGE 90

You can redefine any of the global variable values to change the alerting percent on your system. The
change will take effect the next time the altering levels are checked.
Use IBM i Access Client Solutions (ACS) to generate SQL for the global variable and use the OR REPLACE
option to recreate it with a different default. For example, to send an alert when a file reaches 70% of its
maximum size, use the following SQL statement:

CREATE OR REPLACE VARIABLE SYSIBMADM.QIBM_SYSTEM_LIMITS_ALERT_15000_PERCENTAGE


INTEGER
DEFAULT 70

SYSLIMTBL table
The SYSLIMTBL table contains information about limits as they are being consumed. It is maintained by
Db2 for i.
This table is not authorized or managed like a typical Db2 for i catalog. By default, all users have authority
to view this table. If this table is removed or incompatibly altered, the IBM i operating system will
automatically recreate it. The SYSLIMTBL table is designed to have as small a footprint as possible.
You can add AFTER INSERT or AFTER DELETE triggers to this table. This allows you to perform an action
such as sending a notification when a limit is being logged to the table.
The following table describes the columns in the table. The schema is QSYS2.
Table 259. SYSLIMTBL table

Column Name System Column Name Data Type Description

LAST_CHANGE_TIMESTAMP LASTCHG TIMESTAMP The timestamp when this row was last changed.

Database performance and query optimization 1001


Table 259. SYSLIMTBL table (continued)

Column Name System Column Name Data Type Description

LIMIT_CATEGORY CATEGORY SMALLINT The category of this limit.

0 Database

1 Journal

2 Security

3 Miscellaneous

4 Work management

5 File system

6 Save/restore

7 Cluster

8 Communication

LIMIT_TYPE LIMTYPE SMALLINT The type of limit.

1 Object

2 Job

3 System

4 ASP

LIMIT_ID LIMIT_ID INTEGER Unique identifier for this limit. Values are maintained in the
SIZING_ID column in the QSYS2.SQL_SIZING table.

JOB_NAME JOB_NAME VARCHAR(28) The name of the job that reported the current value.

USER_NAME CURUSER VARCHAR(10) The name of the user in effect when the current value was
updated.

CURRENT_VALUE CURVAL BIGINT Reported value for this limit.

SYSTEM_SCHEMA_NAME SYS_NAME VARCHAR(10) The library name for the object. If no library name, contains the
null value.
Nullable

SYSTEM_OBJECT_NAME SYS_ONAME VARCHAR(30) The object name for this row. If no object name, contains the null
value.
Nullable

SYSTEM_TABLE_MEMBER SYS_MNAME VARCHAR(10) The member name for an object limit specific to database
members. Contains the null value if this row is not for a member
Nullable limit.

OBJECT_TYPE OBJTYPE VARCHAR(7) The IBM i object type when an object name has been logged
in the SYSTEM_SCHEMA_NAME and SYSTEM_OBJECT_NAME
Nullable columns. Contains the null value when no object name is
specified.

ASP_NUMBER ASPNUM SMALLINT Contains the ASP number related to this row. Contains the null
value if there is no ASP number.
Nullable

IFS_PATH_NAME PATHNAME DBCLOB(5000) IFS path for the object. Contains the null value if there is no path.
CCSID 1200
Nullable

Example
Add a trigger to QSYS2.SYSLIMTBL to send a message when any table is approaching the maximum size.
The trigger will be fired when any row is inserted into SYSLIMTBL. Within the trigger, it checks for the
LIMIT_ID indicating the maximum number of rows in a partition (15000) and the value when you want to
be notified.

/* Force any pseudo closed cursors over SYSLIMTBL to be closed */


CL: ALCOBJ OBJ((QSYS2/SYSLIMTBL *FILE *EXCL)) CONFLICT(*RQSRLS) ;
CL: DLCOBJ OBJ((QSYS2/SYSLIMTBL *FILE *EXCL));

CREATE OR REPLACE TRIGGER MYLIB.SYSTEM_LIMITS_LARGE_FILE


AFTER INSERT ON QSYS2.SYSLIMTBL

1002 IBM i: Performance and Query Optimization


REFERENCING NEW AS N FOR EACH ROW MODE DB2ROW
SET OPTION USRPRF=*OWNER, DYNUSRPRF=*OWNER
BEGIN ATOMIC
DECLARE V_CMDSTMT VARCHAR(200) ;
DECLARE "ERROR" INTEGER;
DECLARE EXIT HANDLER FOR SQLEXCEPTION SET "ERROR" = 1;
/* ------------------------------------------------------------------*/
/* If a table is nearing the maximum size, alert the operator */
/* ------------------------------------------------------------------*/
IF (N.LIMIT_ID = 15000 AND
N.CURRENT_VALUE > 3000000000) THEN
SET V_CMDSTMT = 'SNDMSG MSG(''Table: '
CONCAT N.SYSTEM_SCHEMA_NAME CONCAT '/' CONCAT N.SYSTEM_OBJECT_NAME
CONCAT ' (' CONCAT N.SYSTEM_TABLE_MEMBER CONCAT
') IS GETTING VERY LARGE - ROW COUNT = '
CONCAT CURRENT_VALUE CONCAT ' '') TOUSR(*SYSOPR) MSGTYPE(*INFO) ';
CALL QSYS2.QCMDEXC( V_CMDSTMT );
END IF;
END;

SYSLIMITS view
The SYSLIMITS view contains information about limits. This view is built on the QSYS.SYSLIMTBL table
along with other system information. If a job is still active, the view contains information about the job
that logged the limit.
Authorization: For rows where the job is still active, the caller's user profile must be the same as the job
user identity of the job for which the information is being returned, or must have *JOBCTL user special
authority, or QIBM_DB_SQLADM or QIBM_DB_SYSMON function usage authority. If the caller does not
have sufficient authority, partial information is returned along with an SQL warning of '01548'.
For rows where LIMIT_TYPE = 'OBJECT', additional authorization is required:
• If the user has *EXECUTE authority to the library, and both *OBJOPR and *READ authority to an object,
full details are returned.
• Otherwise, partial information is returned along with an SQL warning of '01548'.
The following table describes the columns in the view. The schema is QSYS2.
Table 260. SYSLIMITS view

Column Name System Column Name Data Type Description

LAST_CHANGE_TIMESTAMP LASTCHG TIMESTAMP The timestamp when this row was last changed.

LIMIT_CATEGORY CATEGORY VARCHAR(15) The category for this limit.


• DATABASE
• JOURNAL
• SECURITY
• MISCELLANEOUS
• WORK MANAGEMENT
• FILE SYSTEM
• SAVE RESTORE
• CLUSTER
• COMMUNICATION

LIMIT_TYPE TYPE VARCHAR(7) The type of limit.


• OBJECT
• JOB
• SYSTEM
• ASP

SIZING_NAME SIZING_NAM VARCHAR(128) Name that corresponds to the sizing ID.

COMMENTS COMMENTS VARCHAR(2000) Description of the limit.

Nullable

USER_NAME CURUSER VARCHAR(10) The name of the user in effect when this row was logged.

Database performance and query optimization 1003


Table 260. SYSLIMITS view (continued)

Column Name System Column Name Data Type Description

CURRENT_VALUE CURVAL BIGINT Reported value for this limit.

MAXIMUM_VALUE MAXVAL DECIMAL(21,0) Maximum value allowed for this limit.

Nullable

JOB_NAME JOB_NAME VARCHAR(28) The name of the job when this row was logged.
Contains the null value if the job is no longer active.

JOB_STATUS JOB_STATUS CHAR(10) Status of the job.

Nullable Contains the null value if the job is no longer active.

ACTIVE_JOB_STATUS AJSTATUS CHAR(4) The active status of the initial thread of the job.

Nullable Contains the null value if the job is in transition or is no longer


active.

RUN_PRIORITY RUNPRI INTEGER The highest run priority allowed for any thread within this job.

Nullable Contains the null value if the job is no longer active.

SBS_NAME SBS_NAME CHAR(10) Name of subsystem where job is running.

Nullable Contains the null value if the job is no longer active.

CPU_USED CPU_USED BIGINT The amount of CPU time (in milliseconds) that has been currently
used by this job.
Nullable
Contains the null value if the job is no longer active.

TEMP_STORAGE_USED_MB TEMPSTG INTEGER The amount of auxiliary storage (in megabytes) that is currently
allocated to this job.
Nullable
Contains the null value if the job is no longer active.

AUX_IO_REQUESTED AUXIO BIGINT The number of auxiliary I/O requests performed by the job
across all routing steps. This includes both database and
Nullable nondatabase paging.
Contains the null value if the job is no longer active.

PAGE_FAULTS PAGEFAULT BIGINT The number of times an active program referenced an address
that was not in main storage during the current routing step of
Nullable the specified job.
Contains the null value if the job is no longer active.

CLIENT_WRKSTNNAME CLIENTWRK CHAR(255) Value of the SQL CLIENT_WRKSTNNAME special register.

Nullable Contains the null value if the job is no longer active.

CLIENT_APPLNAME CLIENTAPP CHAR(255) Value of the SQL CLIENT_APPLNAME special register.

Nullable Contains the null value if the job is no longer active.

CLIENT_ACCTNG CLIENTACT CHAR(255) Value of the SQL CLIENT_ACCTNG special register.

Nullable Contains the null value if the job is no longer active.

CLIENT_PROGRAMID CLIENTPGM CHAR(255) Value of the SQL CLIENT_PROGRAMID special register.

Nullable Contains the null value if the job is no longer active.

CLIENT_USERID CLIENTUSER CHAR(255) Value of the SQL CLIENT_USERID special register.

Nullable Contains the null value if the job is no longer active.

SQL_STATEMENT_TEXT SQLSTMT VARCHAR(10000) Statement text of the last SQL statement to run or the SQL
statement that is currently running.
Nullable
Contains the null value if the job is no longer active.

SCHEMA_NAME OBJ_SCHEMA VARCHAR(128) The SQL schema name for this object.

Nullable Contains the null value if there is no schema name.

OBJECT_NAME OBJ_NAME VARCHAR(128) The SQL name for the object.

Nullable Contains the null value if there is no object name or if an SQL


name could not be returned.

1004 IBM i: Performance and Query Optimization


Table 260. SYSLIMITS view (continued)

Column Name System Column Name Data Type Description

SYSTEM_SCHEMA_NAME SYS_NAME VARCHAR(10) The library name for the object.

Nullable Contains the null value if there is no library name.

SYSTEM_OBJECT_NAME SYS_ONAME VARCHAR(30) The object name for this row.

Nullable Contains the null value if there is no object name.

SYSTEM_TABLE_MEMBER SYS_MNAME VARCHAR(10) The member name for an object limit specific to database
members.
Nullable
Contains the null value if this row is not for a member limit.

IFS_PATH_NAME PATHNAME DBCLOB(5000) IFS path for the object.


CCSID 1200
Contains the null value if there is no path.
Nullable

OBJECT_TYPE OBJTYPE VARCHAR(7) The IBM i object type when an object name has been logged
in the SYSTEM_SCHEMA_NAME and SYSTEM_OBJECT_NAME
Nullable columns.
Contains the null value when no object name is specified.

SQL_OBJECT_TYPE SQLOBJTYPE VARCHAR(9) The SQL type of the object when an object name has been logged
in the SYSTEM_SCHEMA_NAME and SYSTEM_OBJECT_NAME
Nullable columns. Values are:
• ALIAS
• FUNCTION
• INDEX
• PACKAGE
• PROCEDURE
• ROUTINE
• SEQUENCE
• TABLE
• TRIGGER
• TYPE
• VARIABLE
• VIEW
• XSR
Contains the null value if the object is not an SQL object or when
no object name is specified.

ASP_NUMBER ASPNUM SMALLINT Contains the ASP number related to this row.

Nullable Contains the null value if there is no ASP number.

LIMIT_ID LIMIT_ID INTEGER Unique identifier for this limit. Values are maintained in the
SIZING_ID column in the QSYS2.SQL_SIZING table.

Examples
• Find the 50 largest IFS stream files. Remove any duplicates from the result. Note that only stream files
that have reached the documented floor and increment values will appear in SYSLIMITS.

SELECT IFS_PATH_NAME, MAX(CURRENT_VALUE) AS MAX_BYTE_SIZE


FROM QSYS2.SYSLIMITS
WHERE LIMIT_ID = 18409
GROUP BY IFS_PATH_NAME
ORDER BY MAX_BYTE_SIZE DESC LIMIT 50;

• Review the consumption of the 'Total number of jobs', relative to the QMAXJOB system value.

WITH TT(JOB_MAXIMUM)
AS (SELECT CURRENT_NUMERIC_VALUE
FROM QSYS2.SYSTEM_VALUE_INFO
WHERE SYSTEM_VALUE_NAME = 'QMAXJOB')
SELECT LAST_CHANGE_TIMESTAMP AS INCREMENT_TIME, CURRENT_VALUE AS JOB_COUNT,
TT.JOB_MAXIMUM,
DEC(DEC(CURRENT_VALUE,19,2) / DEC(TT.JOB_MAXIMUM,19,2) * 100,19,2)

Database performance and query optimization 1005


AS PERCENT_CONSUMED
FROM QSYS2.SYSLIMITS, TT
WHERE LIMIT_ID = 19000 ORDER BY CURRENT_VALUE DESC;

SYSLIMITS_BASIC view
The SYSLIMITS_BASIC view contains information about limits. This view is built on the QSYS.SYSLIMTBL
table along with other system information. It does not return information about the job that logged the
limit. This view returns less information than the SYSLIMITS view, but it requires less authorization and
typically performs significantly better.
Authorization: None required.
The following table describes the columns in the view. The system name is SYSLIMIT_B. The schema is
QSYS2.
Table 261. SYSLIMITS_BASIC view

Column Name System Column Name Data Type Description

LAST_CHANGE_TIMESTAMP LASTCHG TIMESTAMP The timestamp when this row was last changed.

LIMIT_CATEGORY CATEGORY VARCHAR(15) The category for this limit.


• DATABASE
• JOURNAL
• SECURITY
• MISCELLANEOUS
• WORK MANAGEMENT
• FILE SYSTEM
• SAVE RESTORE
• CLUSTER
• COMMUNICATION

LIMIT_TYPE TYPE VARCHAR(7) The type of limit.


• OBJECT
• JOB
• SYSTEM
• ASP

SIZING_NAME SIZING_NAM VARCHAR(128) Name that corresponds to the sizing ID.

COMMENTS COMMENTS VARCHAR(2000) Description of the limit.

Nullable

USER_NAME CURUSER VARCHAR(10) The name of the user in effect when this row was logged.

CURRENT_VALUE CURVAL BIGINT Reported value for this limit.

MAXIMUM_VALUE MAXVAL DECIMAL(21,0) Maximum value allowed for this limit.

Nullable

JOB_NAME JOB_NAME VARCHAR(28) The name of the job when this row was logged.
Contains the null value if the job is no longer active.

SYSTEM_SCHEMA_NAME SYS_NAME VARCHAR(10) The library name for the object.

Nullable Contains the null value if there is no library name.

SYSTEM_OBJECT_NAME SYS_ONAME VARCHAR(30) The object name for this row.

Nullable Contains the null value if there is no object name.

SYSTEM_TABLE_MEMBER SYS_MNAME VARCHAR(10) The member name for an object limit specific to database
members.
Nullable
Contains the null value if this row is not for a member limit.

IFS_PATH_NAME PATHNAME DBCLOB(5000) IFS path for the object.


CCSID 1200
Contains the null value if there is no path.
Nullable

1006 IBM i: Performance and Query Optimization


Table 261. SYSLIMITS_BASIC view (continued)

Column Name System Column Name Data Type Description

OBJECT_TYPE OBJTYPE VARCHAR(7) The IBM i object type when an object name has been logged
in the SYSTEM_SCHEMA_NAME and SYSTEM_OBJECT_NAME
Nullable columns.
Contains the null value when no object name is specified.

ASP_NUMBER ASPNUM SMALLINT Contains the ASP number related to this row.

Nullable Contains the null value if there is no ASP number.

LIMIT_ID LIMIT_ID INTEGER Unique identifier for this limit. Values are maintained in the
SIZING_ID column in the QSYS2.SQL_SIZING table.

Examples
• Review the consumption of the 'Total number of jobs', relative to the QMAXJOB system value.

WITH TT(JOB_MAXIMUM)
AS (SELECT CURRENT_NUMERIC_VALUE
FROM QSYS2.SYSTEM_VALUE_INFO
WHERE SYSTEM_VALUE_NAME = 'QMAXJOB')
SELECT LAST_CHANGE_TIMESTAMP AS INCREMENT_TIME, CURRENT_VALUE AS JOB_COUNT,
TT.JOB_MAXIMUM,
DEC(DEC(CURRENT_VALUE,19,2) / DEC(TT.JOB_MAXIMUM,19,2) * 100,19,2)
AS PERCENT_CONSUMED
FROM QSYS2.SYSLIMITS_BASIC, TT
WHERE LIMIT_ID = 19000 ORDER BY CURRENT_VALUE DESC;

PROCESS_SYSTEM_LIMITS_ALERTS procedure
The QSYS2.PROCESS_SYSTEM_LIMITS_ALERTS procedure can be called directly to look for any tracked
limits that have exceeded their alerting level in the last 24 hours. If any are identified, an alert will be
signaled. Calling it repeatedly can send duplicate alerts.
This procedure performs the same checks that are done by the system processing of the alerts. If a limit
has reached its alerting level, message SQL7062 is sent to the QSYSOPR message queue. See “System
limit alerts” on page 1000 for details.
This procedure can be submitted in a job to be run at a user-determined time to look for runaway
situations.
Authorization: This procedure, implemented by the QSYS2/LIM_ALERTS program, is shipped with
*PUBLIC *EXCLUDE authority.
To call this procedure the user must have *EXECUTE authority to the QSYS2/LIM_ALERTS program.

PROCESS_SYSTEM_LIMITS_ALERTS ( )

The schema is QSYS2.

Example
To schedule a job that will run every weekday at noon to report system limits that have reached their
reporting threshold values in the last 24 hours, the following CL command can be run.

ADDJOBSCDE JOB(chkalert)
CMD(RUNSQL SQL('CALL QSYS2.PROCESS_SYSTEM_LIMITS_ALERTS()') COMMIT(*NONE) )
FRQ(*WEEKLY) SCDDATE(*NONE)
SCDDAY(*MON *TUE *WED *THU *FRI ) SCDTIME('12:00:00')

Database performance and query optimization 1007


QIBM_SYSTEM_LIMITS global variables
To prevent excess storage consumption or retention of unnecessarily old system limits entries within the
QSYS2/SYSLIMTBL table, Db2 for i will automatically delete (or prune) rows.
There are two ways the pruning is controlled. One method is by the number of days to keep a row. The
other is by the maximum number of rows to keep for a specific limit. In each case, Db2 for i supplied
global variables guide the pruning action.
Controls exist for deleting rows that have reached a certain age are handled with a set of Db2 for i
provided global variables. These controls cause rows to be removed when they exceed the number of
days.
The following are the names of the global variables that control pruning by number of days and the limit
that is shipped for each one. The schema is SYSIBMADM.

Global variable Shipped limit


QIBM_SYSTEM_LIMITS_ASP_BY_DAYS 90
QIBM_SYSTEM_LIMITS_JOB_BY_DAYS 90
QIBM_SYSTEM_LIMITS_OBJECT_BY_DAYS 90
QIBM_SYSTEM_LIMITS_SYSTEM_BY_DAYS 90

The second control for automatic deletion of rows is by the number of rows for a type of limit. For each
type of limit, there are two global variables. The pruning variable is used to choose how many of the most
recently logged entries should be retained. The high point variable is used to choose how many of the
highest consumption value entries should be retained.
The following are the names of the global variables and the limit that is shipped for each one. The schema
is SYSIBMADM.

Global variable Shipped limit


QIBM_SYSTEM_LIMITS_PRUNE_BY_ASP 20
QIBM_SYSTEM_LIMITS_PRUNE_BY_JOB 20
QIBM_SYSTEM_LIMITS_PRUNE_BY_OBJECT 20
QIBM_SYSTEM_LIMITS_PRUNE_BY_SYSTEM 20
QIBM_SYSTEM_LIMITS_SAVE_HIGH_POINTS_BY_ASP 25
QIBM_SYSTEM_LIMITS_SAVE_HIGH_POINTS_BY_JOB 5
QIBM_SYSTEM_LIMITS_SAVE_HIGH_POINTS_BY_OBJECT 5
QIBM_SYSTEM_LIMITS_SAVE_HIGH_POINTS_BY_SYSTEM 25

You can adjust any of the global variable values to establish a custom behavior for the automatic deletion
of system limits rows. The Db2 for i supplied global variables use the default value to guide an automatic
row deletion process that runs nightly when Collection Services is recycled, which normally occurs just
past midnight.
Authorization: To create or replace a global variable the caller must have:
• *OBJMGT authority on the service program for the variable, and
• All authorities needed to DROP the variable, and
• *READ authority on the SYSVARIABLES catalog table.

1008 IBM i: Performance and Query Optimization


Use IBM i Access Client Solutions (ACS) to generate SQL for the global variable and use the OR REPLACE
option to recreate it with a different default. For example, to remove all object limits older than 30 days,
use the following SQL statement:

CREATE OR REPLACE VARIABLE SYSIBMADM.QIBM_SYSTEM_LIMITS_OBJECT_BY_DAYS


INTEGER
DEFAULT 30

Work Management Services


These views and functions provide system value and job information.

ACTIVE_JOB_INFO table function


The ACTIVE_JOB_INFO table function returns one row for every active job.
The information returned is similar to the detail seen from the Work with Active Jobs (WRKACTJOB)
command and the List Job (QUSLJOB) API. The ACTIVE_JOB_INFO table function has two uses:
1. To see details for all, or a subset of, active jobs. A subset of active jobs can be requested by using the
optional filter parameters.
2. To measure elapsed statistics for active jobs. You can use an optional parameter to reset statistics,
similar to the WRKACTJOB command F10 Restart Statistics function. Measurements will be calculated
based on this new starting point.
Authorization: None required to see general information or to see information for jobs where the caller's
user profile is the same as the job user identity of the job for which the information is being returned.
For DETAILED_INFO => NONE or DETAILED_INFO => WORK:
• None required.
For DETAILED_INFO => QTEMP:
• The caller must have *JOBCTL special authority.
For DETAILED_INFO => ALL:
• None required to see detailed column information for the columns that are
included with DETAILED_INFO => WORK or the CLIENT_IP_ADDRESS, PAGE_FAULTS,
PRESTART_JOB_REUSE_COUNT, PRESTART_JOB_MAX_USE_COUNT, and WORKLOAD_GROUP columns.
• A caller who is authorized to the QIBM_DB_SQLADM or QIBM_DB_SYSMON function usage identifiers
can see detailed column information related to SQL activity starting with the SQL_STATEMENT_TEXT
column through the PSEUDO_CLOSED_CURSOR_COUNT column.
• A caller with *JOBCTL special authority can see all detailed column information.

Database performance and query optimization 1009


ACTIVE_JOB_INFO (
reset-statistics
RESET_STATISTICS =>

, subsystem-list-filter
SUBSYSTEM_LIST_FILTER =>

, job-name-filter
JOB_NAME_FILTER =>

, current-user-list-filter
CURRENT_USER_LIST_FILTER =>

)
, detailed-info
DETAILED_INFO =>

The schema is QSYS2.

reset- A character or graphic string expression that contains a value of YES or NO.
statistics
If this parameter has a value of YES, statistics are reset such that the time of this query
execution is used as the new baseline. Future invocations of ACTIVE_JOB_INFO within
this connection will return statistical detail relative to the new baseline. If this parameter
has a value of NO, statistics are not reset for the invocation unless the subsystem-list-filter
or job-name-filter parameter values are different than the previous invocation. Changing
the filter values will always cause statistics to be reset. If this parameter is not specified,
the default is NO.
The first invocation of ACTIVE_JOB_INFO within a connection will always perform an
implicit reset, regardless of whether a reset was explicitly requested.

subsystem- A character or graphic string expression that contains a list of up to 25 subsystem names
list-filter separated by exactly one comma. The filter determines which subsystems to use to
return job information.
If this parameter is not specified, is an empty string, or is the null value, information for
all subsystems is returned.

job-name- A character or graphic string expression that contains an unqualified job name that
filter determines the job information to be returned. The name can be a generic name.
The string can be one of the following special values:

* Only information for the current job is returned.


*ALL Information for all jobs is returned.
*CURRENT Information for all jobs with a job name that is the same as the current job
is returned.
*SBS Information for all active subsystem monitors is returned.
*SYS Information for all active system jobs is returned. When using this value,
the subsystem-list-filter must not be specified or must be the null value.

1010 IBM i: Performance and Query Optimization


If this parameter is not specified, is an empty string, or is the null value, information for
all jobs is returned.

current-user- A character or graphic string expression that contains a list of up to 10 user profile names
list-filter separated by exactly one comma. The filter determines which current user values to use
to return job information.
If this parameter is not specified, is an empty string, or is the null value, information for
all users is returned.

detailed-info A character or graphic string expression that indicates the type of information to be
returned.

NONE Only the general information is returned for active jobs. This is the information
in the columns prior to the JOB_DESCRIPTION_LIBRARY column. This is the
default.
WORK In addition to the general information for active jobs, additional work
management information is returned.
QTEMP In addition to the general information for active jobs, the QTEMP_SIZE column
is returned.
ALL Information for all the columns is returned.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
The DETAILED_INFO option column indicates which of the DETAILED_INFO parameter values can return
a non-null value for the corresponding result column.
Table 262. ACTIVE_JOB_INFO table function

DETAILED_INFO
Column Name Data Type option Description

ORDINAL_POSITION INTEGER NONE A unique number for each row.


WORK
QTEMP
ALL

JOB_NAME VARCHAR(28) NONE The qualified job name.


WORK
QTEMP
ALL

JOB_NAME_SHORT VARCHAR(10) NONE The name of the job.


WORK
QTEMP
ALL

JOB_USER VARCHAR(10) NONE The user profile that started the job.
WORK
QTEMP
ALL

JOB_NUMBER VARCHAR(6) NONE The job number of the job.


WORK
QTEMP
ALL

INTERNAL_JOB_ID BINARY(16) NONE The internal job identifier.


WORK
QTEMP
ALL

SUBSYSTEM VARCHAR(10) NONE The name of the subsystem where the job is running.
WORK Contains the null value if the job is a system job.
QTEMP
ALL

Database performance and query optimization 1011


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

SUBSYSTEM_LIBRARY_NAME VARCHAR(10) NONE Library containing the subsystem description.


WORK Contains the null value if the job is a system job.
QTEMP
ALL

AUTHORIZATION_NAME VARCHAR(10) NONE The user profile under which the initial thread is running at this
WORK time. For jobs that swap user profiles, this user profile name and
QTEMP the user profile that initiated the job can be different.
ALL

JOB_TYPE VARCHAR(3) NONE Type of active job.


WORK
QTEMP ASJ Autostart
ALL BCH Batch

BCI Batch Immediate

EVK Started by a procedure start request

INT Interactive

M36 Advanced 36 server job

MRT Multiple requester terminal

PDJ Print driver job

PJ Prestart job

RDR Spool reader

SBS Subsystem monitor

SYS System

WTR Spool writer

1012 IBM i: Performance and Query Optimization


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

FUNCTION_TYPE VARCHAR(3) NONE The type of function described in the FUNCTION column.
WORK
QTEMP CMD The FUNCTION column contains the name of the
ALL command being run.

DLY The initial thread of the job is processing a DLYJOB


(Delay Job) command. The FUNCTION column contains
a time that is the number of seconds the job is delayed
(up to 999999 seconds), or the time when job is to
resume processing (hh:mm:ss).

GRP The FUNCTION column contains the group name of a


suspended group job.

I/O The job is a subsystem monitor that is performing


input/output operations (I/O) to a work station for the
sign-on display file. The FUNCTION column contains
the name of the work station device.

IDX The FUNCTION column contains the name of the file


associated with an index rebuild operation.

JVM The initial thread of the job is running a Java Virtual


Machine. The FUNCTION column contains the name of
the java class.

LOG The FUNCTION column contains QHST to indicate


history information is being logged to a database file.

MNU The FUNCTION column contains the name of the


menu.

MRT The job is either a multiple requester terminal (MRT)


job if JOB_TYPE is BCH, or it is an interactive job
attached to an MRT job if JOB_TYPE is INT.
For an MRT job, the FUNCTION column contains
information in the following format:
• CHAR(2): The number of requesters currently
attached to the MRT job.
• CHAR(1): Contains a / (slash).
• CHAR(2): The maximum number of requesters.
• CHAR(1): Contains a blank.
• CHAR(3): The never-ending program (NEP) indicator.
A value of NEP indicates a never-ending program. A
value of blanks indicates that it is not a never-ending
program.
• CHAR(1): Contains a blank.
For an interactive job attached to an MRT, the
FUNCTION column contains the name of the MRT
procedure.

PGM The FUNCTION column contains the name of a


program.

PRC The FUNCTION column contains the name of a


procedure.

USR The FUNCTION column contains the user-specified


function set with the Change Current Job (QWCCCJOB)
API.

Contains the null value if none of these values apply.

Database performance and query optimization 1013


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

FUNCTION VARCHAR(10) NONE The last high-level function initiated by the initial thread.
WORK If FUNCTION_TYPE is not null, contains a value as defined by
QTEMP the FUNCTION_TYPE column. Otherwise, can contain one of the
ALL following values:

ADLACTJOB Auxiliary storage is being allocated for the


number of active jobs specified in the
QADLACTJ system value.

ADLTOTJOB Auxiliary storage is being allocated for the


number of jobs specified in the QADLTOTJ
system value.

CMDENT The command entry display is being used.

COMMIT The initial thread of the job is performing a


commit operation.

DIRSHD This job is running under the directory


shadowing function.

DLTSPF A spooled file is being deleted.

DUMP A dump is in process.

JOBIDXRCY A damaged job index is being recovered.

JOBLOG A job log is being produced.

JOBLOGQRCY The job log server queue is being recovered


or rebuilt.

PASSTHRU The job is a pass-through job.

RCLSPLSTG Empty spooled database members are being


deleted.

ROLLBACK The initial thread of the job is performing a


rollback operation.

SPLCLNUP A cleanup of jobs on job queues and spooled


files is being performed.

Contains the null value if a logged function has not been


performed.

1014 IBM i: Performance and Query Optimization


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

JOB_STATUS VARCHAR(4) NONE The status of the initial thread of the job. The following list
WORK contains some of the most common values. For a complete list
QTEMP of values, see Work Management API Attribute Descriptions in
ALL Application Programming Interfaces

CMNW Waiting for the completion of an I/O operation to a


communications device.

CNDW Waiting on handle-based condition.

DEQW Waiting for completion of a dequeue operation.

DLYW Due to the Delay Job (DLYJOB) command, the initial


thread of the job is delayed while it waits for a time
interval to end, or for a specific delay end time.

DSPW Waiting for input from a work station display.

END The job has been ended with the *IMMED option, or
its delay time has ended with the *CNTRLD option.

EOJ Ending for a reason other than running the End Job
(ENDJOB) or End Subsystem (ENDSBS) command.

EVTW Waiting for an event.

HLD The job is being held.

JVAW Waiting for completion of a Java program operation.

LCKW Waiting for a lock.

LSPW Waiting for a lock space to be attached.

MSGW Waiting for a message from a message queue.

MTXW Waiting for a mutex.

PSRW A prestart job waiting for a program start request.

RUN Job is currently running.

SEMW Waiting for a semaphore.

THDW Waiting for another thread to complete an operation.

MEMORY_POOL VARCHAR(9) NONE The identifier of the system-related pool from which the job's
WORK main storage is allocated. This is the pool that the threads in the
QTEMP job start in.
ALL

RUN_PRIORITY INTEGER NONE The priority at which the job competes for the processing unit
WORK relative to other jobs that are active at the same time. The run
QTEMP priority ranges from 1 (highest priority) to 99 (lowest priority).
ALL

THREAD_COUNT INTEGER NONE The number of active threads in the job.


WORK
QTEMP
ALL

TEMPORARY_STORAGE INTEGER NONE The amount of temporary storage, in megabytes, that is


WORK currently allocated to this job.
QTEMP
ALL

CPU_TIME DECIMAL(20,0) NONE The total processing unit time used by the job, in milliseconds.
WORK
QTEMP
ALL

TOTAL_DISK_IO_COUNT DECIMAL(20,0) NONE The total number of disk I/O operations performed by the job
WORK across all routing steps. This is the sum of the asynchronous and
QTEMP synchronous disk I/O.
ALL

Database performance and query optimization 1015


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

ELAPSED_INTERACTION_COUNT INTEGER NONE The number of interactions. This is the number of operator
WORK interactions during the measurement time interval.
QTEMP Contains the null value if the job is not interactive.
ALL

ELAPSED_TOTAL_RESPONSE_TIME INTEGER NONE The total response time over the measurement time interval, in
WORK seconds.
QTEMP Contains the null value if the job is not interactive.
ALL

ELAPSED_TOTAL_DISK_IO_COUNT DECIMAL(20,0) NONE The number of disk I/O operations performed by the job
WORK during the measurement time interval. This is the sum of the
QTEMP asynchronous and synchronous disk I/O.
ALL

ELAPSED_ASYNC_DISK_IO_COUNT DECIMAL(20,0) NONE The number of asynchronous (physical) disk I/O operations
WORK performed by the job during the measurement time interval.
QTEMP This value is the sum of the asynchronous database and
ALL nondatabase reads and writes.

ELAPSED_SYNC_DISK_IO_COUNT DECIMAL(20,0) NONE The number of synchronous (physical) disk I/O operations
WORK performed by the job during the measurement time interval.
QTEMP This value is the sum of the synchronous database and
ALL nondatabase reads and writes.

ELAPSED_CPU_PERCENTAGE DECIMAL(10,2) NONE The percent of processing unit time attributed to this job during
WORK the measurement time interval.
QTEMP
ALL

ELAPSED_CPU_TIME DECIMAL(20,0) NONE The total CPU time spent during the measurement time interval,
WORK in milliseconds.
QTEMP
ALL

ELAPSED_PAGE_FAULT_COUNT DECIMAL(20,0) NONE The number of times an active program referenced an address
WORK that is not in main storage for the specified job during the
QTEMP measurement time interval.
ALL

JOB_END_REASON VARCHAR(60) NONE Reason the job is ending. Contains one of the following values:
WORK • JOB ENDED DUE TO A DEVICE ERROR
QTEMP
ALL • JOB ENDED DUE TO A SIGNAL
• JOB ENDED DUE TO AN UNHANDLED ERROR
• JOB ENDED DUE TO THE CPU LIMIT BEING EXCEEDED
• JOB ENDED DUE TO THE DISCONNECT TIME INTERVAL
BEING EXCEEDED
• JOB ENDED DUE TO THE INACTIVITY TIME INTERVAL BEING
EXCEEDED
• JOB ENDED DUE TO THE MESSAGE SEVERITY LEVEL BEING
EXCEEDED
• JOB ENDED DUE TO THE STORAGE LIMIT BEING EXCEEDED
• JOB ENDED WHILE IT WAS STILL ON A JOB QUEUE
• JOB ENDING ABNORMALLY
• JOB ENDING IMMEDIATELY
• JOB ENDING IN NORMAL MANNER
• JOB ENDING NORMALLY AFTER A CONTROLLED END WAS
REQUESTED
• SYSTEM ENDED ABNORMALLY
Contains the null value if job is not currently ending.

SERVER_TYPE VARCHAR(30) NONE The type of server represented by the job. See Server table for a
WORK list of server type values.
QTEMP Contains the null value if the job is not part of a server.
ALL

1016 IBM i: Performance and Query Optimization


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

ELAPSED_TIME DECIMAL(20,3) NONE The time that has elapsed, in seconds, between the
WORK measurement start time and the current system time.
QTEMP
ALL

JOB_DESCRIPTION_LIBRARY VARCHAR(10) WORK The name of the library containing the job description.
ALL Contains the null value if the job has no job description.

JOB_DESCRIPTION VARCHAR(10) WORK The name of the job description used for this job.
ALL Contains the null value if the job has no job description.

JOB_QUEUE_LIBRARY VARCHAR(10) WORK The name of the library containing the job queue.
ALL Contains the null value if the job is not a batch job that was
started from a job queue.

JOB_QUEUE VARCHAR(10) WORK The name of the job queue that the job was on.
ALL Contains the null value if the job is not a batch job that was
started from a job queue.

OUTPUT_QUEUE_LIBRARY VARCHAR(10) WORK The name of the library that contains the default output queue.
ALL Contains the null value if the job has no default output queue.

OUTPUT_QUEUE VARCHAR(10) WORK The name of the default output queue that is used for spooled
ALL output produced by this job. The default output queue is only
used by spooled printer files that specify *JOB for the output
queue.
Contains the null value if the job has no default output queue.

WORKLOAD_GROUP VARCHAR(10) WORK The name of the workload group to which the job belongs.
ALL Contains the null value if the job is not part of a workload group.

CCSID INTEGER WORK The coded character set identifier (CCSID) used for this job.
ALL

DEFAULT_CCSID INTEGER WORK The default coded character set identifier used for this job.
ALL

SORT_SEQUENCE_LIBRARY VARCHAR(10) WORK The name of the library that contains the sort sequence table.
ALL Contains the null value if no sort sequence table is defined for
this job or if SORT_SEQUENCE is a special value.

SORT_SEQUENCE VARCHAR(10) WORK The name of the sort sequence table associated with this job.
ALL Contains the null value if no sort sequence table is defined for
this job.

LANGUAGE_ID CHAR(3) WORK The language identifier associated with this job.
ALL

DATE_FORMAT CHAR(4) WORK The date format used for this job.
ALL
*DMY Day, month, year format.

*JUL Julian format (year and day).

*MDY Month, day, year format.

*YMD Year, month, day format.

DATE_SEPARATOR CHAR(1) WORK The date separator used for this job.
ALL

TIME_SEPARATOR CHAR(1) WORK The time separator used for this job.
ALL

Database performance and query optimization 1017


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

DECIMAL_FORMAT VARCHAR(6) WORK The decimal format used for this job.
ALL
*BLANK Uses a period for a decimal point, a comma for
a 3-digit grouping character, and zero-suppress to
the left of the decimal point.

J Uses a comma for a decimal point and a period for


a 3-digit grouping character. The zero-suppression
character is in the second position (rather than the
first) to the left of the decimal notation. Balances
with zero values to the left of the comma are
written with one leading zero (0,04). The J entry
also overrides any edit codes that might suppress
the leading zero.

I Uses a comma for a decimal point, a period for


a 3-digit grouping character, and zero-suppress to
the left of the decimal point.

TIMEZONE_DESCRIPTION VARCHAR(10) ALL The name of the time zone description that is used to calculate
local job time.

TIMEZONE_CURRENT_OFFSET INTEGER ALL The offset, in minutes, used to calculate local job time. This
value has been adjusted for Daylight Saving Time, if necessary.

TIMEZONE_FULL_NAME VARCHAR(50) ALL The full, or long, name for the time zone. This column returns
either the standard or Daylight Saving Time full name depending
on whether or not Daylight Saving Time is in effect.
Contains the null value if the time zone description uses a
message to specify the current full name and the message
cannot be retrieved.

TIMEZONE_ABBREVIATED_NAME VARCHAR(10) ALL The abbreviated, or short, name for the time zone. This column
returns either the standard or Daylight Saving Time abbreviated
name depending on whether or not Daylight Saving Time is in
effect.
Contains the null value if the time zone description uses a
message to specify the current abbreviated name and the
message cannot be retrieved.

1018 IBM i: Performance and Query Optimization


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

JOB_TYPE_ENHANCED VARCHAR(28) WORK The combined job type and job subtype values.
ALL
ALTERNATE_SPOOL_USER Batch - alternate
spool user

AUTOSTART Autostart job

BATCH Batch job

BATCH_IMMEDIATE Batch immediate


job

BATCH_MRT Batch - System/36


multiple requester
terminal (MRT) job

COMM_PROCEDURE_START_REQUEST Communications
job - procedure
start request job

INTERACTIVE Interactive job

INTERACTIVE_GROUP Interactive job -


Part of group

INTERACTIVE_SYSREQ Interactive job -


Part of system
request pair

INTERACTIVE_SYSREQ_AND_GROUP Interactive job -


Part of system
request pair and
part of a group

PRESTART Prestart job

PRESTART_BATCH Prestart batch job

PRESTART_COMM Prestart
communications job

READER Reader job

SUBSYSTEM Subsystem job

SYSTEM System job (all


system jobs
including SCPF)

WRITER Writer job (including


both spool writers
and print drivers)

JOB_ENTERED_SYSTEM_TIME TIMESTAMP(0) WORK The timestamp for when the job was placed on the system.
ALL

JOB_ACTIVE_TIME TIMESTAMP(0) WORK The timestamp for when the job began to run on the system.
ALL

CLIENT_IP_ADDRESS VARCHAR(45) ALL Client IP address, in IPv4 format, being used by the job.
Contains the null value when no client IP address exists or the
job is using IPv6.

Database performance and query optimization 1019


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

JOB_USER_IDENTITY_SETTING VARCHAR(11) ALL The method by which the job user identity was set.

APPLICATION The job user identity was explicitly set by an


application using one of the Set Job User
Identity APIs, QWTSJUID or QwtSetJuid().
The job may be running either single
threaded or multithreaded.

DEFAULT The job is currently running single threaded


and the job user identity is the name of the
user profile under which the job is currently
running.

SYSTEM The job is currently running multithreaded


and the job user identity was implicitly
set by the system when the job became
multithreaded. It was set to the name of the
user profile that the job was running under
when it became multithreaded.

JOB_USER_IDENTITY VARCHAR(10) ALL The user profile name by which the job is known to other jobs
on the system. The job user identity is used for authorization
checks when other jobs on the system attempt to operate
against the job.
Contains the null value if the user profile no longer exists.

DBCS_CAPABLE VARCHAR(3) ALL Whether the job is DBCS-capable.

NO The job is not DBCS-capable.

YES The job is DBCS-capable.

SIGNAL_STATUS VARCHAR(3) ALL Whether the job is enabled to receive signals from another job
or the system.

NO The job is not enabled for signals. This job cannot


receive signals from another job or the system.

YES The job is enabled for signals. This job can receive
signals from another job or the system.

MESSAGE_REPLY VARCHAR(3) ALL Whether the job is waiting for a reply to a specific message.

NO The job is not waiting for a reply to a message.

YES The job is waiting for a reply to a message.

Contains the null value if the job is not in message wait status.

END_STATUS VARCHAR(3) ALL Whether the system issued a controlled cancellation.

NO The system, subsystem, or job is not canceled.

YES The system, the subsystem in which the job is running,


or the job itself is canceled.

CANCEL_KEY VARCHAR(3) ALL Whether the user pressed the cancel key.

NO The user did not press the cancel key.

YES The user pressed the cancel key.

EXIT_KEY VARCHAR(3) ALL Whether the user pressed the exit key.

NO The user did not press the exit key.

YES The user pressed the exit key.

MAXIMUM_ACTIVE_THREADS INTEGER ALL The maximum number of threads that a job can run with at
any time. If multiple threads are initiated simultaneously, this
value may be exceeded. If this maximum value is exceeded,
the excess threads will be allowed to run to their normal
completion. Initiation of additional threads will be inhibited until
the maximum number of threads in the job drops below this
maximum value.
Contains the null value if there is no maximum.

1020 IBM i: Performance and Query Optimization


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

SYSTEM_POOL_ID INTEGER ALL The identifier of the system-related pool from which main
storage is currently being allocated for the job's initial thread.
These identifiers are not the same as those specified in the
subsystem description, but are the same as the system pool
identifiers shown on the system status display. If a thread
reaches its time-slice end, the pool the thread is running in can
be switched based on the job's time-slice end pool value. The
current system pool identifier returned will be the actual pool in
which the initial thread of the job is running.
Contains the null value if the value is not available.

POOL_NAME VARCHAR(10) ALL The name of the memory pool in which the job started running.
The name may be a number, in which case it is a private pool
associated with a subsystem. Can contain one of the following
special values:

*BASE This job is running in the base system


pool, which can be shared with other
subsystems.

*INTERACT This job is running in the shared pool


used for interactive work.

*MACHINE This job is running in the machine pool.

*SHRPOOL1 - This job is running in the identified


*SHRPOOL60 shared pool.

*SPOOL This job is running in the shared pool for


spooled writers.

Contains the null value if the value is not available.

QTEMP_SIZE INTEGER The amount of storage, in megabytes, used by objects in


QTEMP the job's temporary library (QTEMP). Objects that are locked,
ALL damaged, or not authorized are not included.
Contains the null value if the size cannot be returned.

PEAK_TEMPORARY_STORAGE INTEGER ALL The maximum amount of auxiliary storage, in megabytes, that
the job has used.

DEFAULT_WAIT INTEGER ALL The default maximum time, in seconds, that a thread in the job
waits for a system instruction, such as a LOCK machine interface
(MI) instruction, to acquire a resource.
Contains the null value if there is no maximum or if the value is
not available.

MAXIMUM_PROCESSING_TIME_ INTEGER ALL The maximum processing unit time, in milliseconds, that the job
ALLOWED can use. If the job consists of multiple routing steps, this is the
maximum processing unit time that the current routing step can
use. If the maximum time is exceeded, the job is held.
Contains the null value if no maximum amount of processing
unit time has been defined.

MAXIMUM_TEMPORARY_STORAGE_ INTEGER ALL The maximum amount of auxiliary storage, in megabytes, that
ALLOWED the job can use. If the job consists of multiple routing steps,
this is the maximum temporary storage that the routing step can
use. This temporary storage is used for storage required by the
program itself and by implicitly created internal system objects
used to support the routing step. (It does not include storage
for objects in the QTEMP library.) If the maximum temporary
storage is exceeded, the job is held. This does not apply to the
use of permanent storage, which is controlled through the user
profile.
Contains the null value if no maximum amount of temporary
storage has been defined.

Database performance and query optimization 1021


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

TIME_SLICE INTEGER ALL The maximum amount of processor time, in milliseconds, given
to each thread in this job before other threads in this job and
in other jobs are given the opportunity to run. The time slice
establishes the amount of time needed by a thread in this job
to accomplish a meaningful amount of processing. At the end of
the time slice, the thread might be put in an inactive state so
that other threads can become active in the storage pool. Values
range from 8 through 9999999.
Contains the null value if the value is not available.

PAGE_FAULTS BIGINT ALL The number of times an active program referenced an address
that was not in main storage during the current routing step of
the specified job.

TOTAL_RESPONSE_TIME BIGINT ALL The total amount of response time for the initial thread, in
milliseconds. This value does not include the time used by the
machine, by the attached input/output (I/O) hardware, and by
the transmission lines for sending and receiving data. Returns
zero for jobs that have no interactions. A value of -1 is returned
if the field is not large enough to hold the actual result.

INTERACTIVE_TRANSACTIONS INTEGER ALL The count of operator interactions, such as pressing the Enter
key or a function key. Returns zero for jobs that have no
interactions.

DATABASE_LOCK_WAITS INTEGER ALL The number of times that the initial thread had to wait to obtain
a database lock.

NON_DATABASE_LOCK_WAITS INTEGER ALL The number of times that the initial thread had to wait to obtain
a nondatabase lock.

INTERNAL_MACHINE_ INTEGER ALL The number of times that the initial thread had to wait to obtain
LOCK_WAITS an internal machine lock.

DATABASE_LOCK_WAIT_TIME INTEGER ALL The cumulative amount of time, in milliseconds, that the initial
thread has had to wait to obtain database locks.

NON_DATABASE_LOCK_WAIT_TIME INTEGER ALL The cumulative amount of time, in milliseconds, that the initial
thread has had to wait to obtain nondatabase locks.

INTERNAL_MACHINE_LOCK_ INTEGER ALL The cumulative amount of time, in milliseconds, that the initial
WAIT_TIME thread has had to wait to obtain internal machine locks.

SQL_STATEMENT_TEXT VARCHAR(10000) ALL Statement text of the last SQL statement to run or the SQL
statement that is currently running. The statement text will be
truncated if it is longer than the column.
Contains the null value if no SQL statement has been run.

SQL_STATEMENT_STATUS VARCHAR(8) ALL The status of SQL within this job.

ACTIVE An SQL statement is currently running

COMPLETE At least one SQL statement has run and has


completed

Contains the null value if no SQL statement has been run.

SQL_STATEMENT_START_TIMESTAMP TIMESTAMP ALL The timestamp of the execution start for an active SQL
statement.
Contains the null value if there is no active SQL statement.

SQL_STATEMENT_NAME VARCHAR(128) ALL The name of the SQL statement.


Contains the null value when the SQL statement has no name.

SQL_STATEMENT_LIBRARY_NAME VARCHAR(10) ALL The library name for the SQL statement object.
Contains the null value when the SQL statement name is null
or when the SQL statement does not exist within a permanent
object.

1022 IBM i: Performance and Query Optimization


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

SQL_STATEMENT_OBJECT_NAME VARCHAR(10) ALL The name of the object which contains the last SQL statement
executed in the job. When the current SQL statement belongs to
an SQL function or an SQL procedure, the object name will be
the external program name.
Contains the null value when the SQL statement name is null
or when the SQL statement does not exist within a permanent
object.

SQL_STATEMENT_OBJECT_TYPE VARCHAR(7) ALL The type of object containing the current SQL statement.

*PGM The current SQL statement resides within a


program.

*SQLPKG The current SQL statement resides within an SQL


package.

*SRVPGM The current SQL statement resides within a


service program.

Contains the null value when the SQL statement object name is
null.

QUERY_OPTIONS_LIBRARY_NAME VARCHAR(10) ALL The name of the QAQQINI options library in use for this job.

SQL_ACTIVATION_GROUP_COUNT INTEGER ALL The number of activation groups, current and ended, that have
executed SQL statements for the job.
Contains the null value if no SQL statement has been run.

SQL_DESCRIPTOR_COUNT BIGINT ALL The number of SQL descriptors that are active for the job.
Contains the null value if no SQL descriptors are active for the
job.

SQL_LOB_LOCATOR_COUNT INTEGER ALL The number of LOB locators that are active for the job.
Contains the null value if no LOB locators are active for the job.

CLI_HANDLE_COUNT BIGINT ALL The number of SQL Call Level Interface (CLI) handles that are
active for the job. This count includes CLI statement handles,
descriptor handles, environment handles, and connection
handles.
Contains the null value if no CLI handles are active for the job.

SQL_SERVER_MODE VARCHAR(3) ALL Indicates whether the job is configured to use SQL Server Mode.

NO The job is not configured to use SQL Server Mode.

YES The job is configured to use SQL Server Mode.

CLIENT_ACCTNG VARCHAR(255) ALL Value of the SQL CURRENT CLIENT_ACCTNG special register.
The value can be null. For more information, see CURRENT
CLIENT_ACCTNG.

CLIENT_APPLNAME VARCHAR(255) ALL Value of the SQL CURRENT CLIENT_APPLNAME special register.
The value can be null. For more information, see CURRENT
CLIENT_APPLNAME.

CLIENT_PROGRAMID VARCHAR(255) ALL Value of the SQL CURRENT CLIENT_PROGRAMID special


register. The value can be null. For more information, see
CURRENT CLIENT_PROGRAMID.

CLIENT_USERID VARCHAR(255) ALL Value of the SQL CURRENT CLIENT_USERID special register.
The value can be null. For more information, see CURRENT
CLIENT_USERID.

CLIENT_WRKSTNNAME VARCHAR(255) ALL Value of the SQL CURRENT CLIENT_WRKSTNNAME special


register. The value can be null. For more information, see
CURRENT CLIENT_WRKSTNNAME.

ROUTINE_TYPE CHAR(1) ALL For a routine defined using SQL, the type of the currently
executing routine.

F Function

P Procedure

Contains the null value if there is no SQL routine currently


executing.

Database performance and query optimization 1023


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

ROUTINE_SCHEMA VARCHAR(128) ALL For a routine defined using SQL, the schema name of the
currently executing routine.
Contains the null value if there is no SQL routine currently
executing.

ROUTINE_SPECIFIC_NAME VARCHAR(128) ALL For a routine defined using SQL, the name of the currently
executing routine.
Contains the null value if there is no SQL routine currently
executing.

CLIENT_PORT INTEGER ALL The port number used by the current client to communicate
with the server.
Contains the null value if the target job does not correspond to a
connection formed using the TCP/IP protocol.

CLIENT_HOST VARCHAR(255) ALL The host name used by the current client to communicate with
the server.
Contains the null value if the target job does not correspond to a
connection formed using the TCP/IP protocol.

INTERFACE_NAME VARCHAR(127) ALL The client database interface name.


Contains the null value if there is no client database interface
name.

INTERFACE_TYPE VARCHAR(63) ALL The client database interface type.


Contains the null value if there is no client database interface
type.

INTERFACE_LEVEL VARCHAR(63) ALL The client database interface level in the following form:
"VVRRMMFP". VV - Version RR - Release MM - Modification level
FP - Fix pack level (only applicable for certain interfaces).
Contains the null value if there is no client database interface
level.

SERVER_MODE_CONNECTING_JOB VARCHAR(28) ALL The qualified job name of the job that established the SQL
Server Mode connection. If the job name is QSQSRVR, then the
qualified job name of the connecting job is returned.
Contains the null value if the job name is not QSQSRVR or
JOB_STATUS is PSRW.

SERVER_MODE_CONNECTING_THREAD BIGINT ALL If the job name is QSQSRVR and the server mode job is in use,
the thread identifier of the last thread to use this connection
is returned. When SQL_STATEMENT_STATUS is COMPLETE, this
application thread identifier might no longer exist.
Contains the null value if the job name is not QSQSRVR or
JOB_STATUS is PSRW.

PRESTART_JOB_REUSE_COUNT INTEGER ALL The number of times the prestart job has been used. The
prestart job reuse count is incremented when a disconnect is
processed for a prestart job. When the prestart job reuse count
exceeds the prestart job maximum number of uses, the job is
ended.
Contains the null value if the job is not a prestart job.

PRESTART_JOB_MAX_USE_COUNT INTEGER ALL The maximum number of times the prestart job can be used
before it is ended. A value of -1 is returned for *NOMAX.
Contains the null value if the job is not a prestart job.

AVAILABLE_RESULT_SETS INTEGER ALL The current count of unconsumed SQL result sets for the job.
Contains the null value if the job has no unconsumed SQL result
sets.

UNCONSUMED_RESULT_SETS INTEGER ALL The cumulative count of unconsumed SQL result sets that were
discarded for the job.
Contains the null value if the job has no unconsumed SQL result
sets that have been discarded.

OPEN_CURSOR_COUNT INTEGER ALL The number of SQL cursors that are currently open for the job.
Contains the null value if no SQL cursors are currently open for
the job.

1024 IBM i: Performance and Query Optimization


Table 262. ACTIVE_JOB_INFO table function (continued)

DETAILED_INFO
Column Name Data Type option Description

FULL_OPEN_CURSOR_COUNT BIGINT ALL The total number of SQL cursors that have been full opened for
the life of the job.
Contains the null value if no SQL cursors have been full opened
during the life of the job.

PSEUDO_OPEN_CURSOR_COUNT BIGINT ALL The total number of SQL cursors that have been pseudo opened
for the life of the job. Pseudo opens are also known as reused
SQL cursors.
Contains the null value if no SQL cursors have been pseudo
opened during the life of the job.

PSEUDO_CLOSED_CURSOR_COUNT INTEGER ALL The active number of pseudo closed SQL cursors within the
job. Pseudo closed cursors are cursors that have been closed
by the application, but remain open within the database. A
pseudo closed cursor may be reused when the same query is
executed many times, resulting in a performance improvement
on the open. Conversely, accumulating too many pseudo closed
cursors within the job can have a negative impact on the storage
footprint of the job.
Contains the null value if no SQL cursors are pseudo closed.

CQE_CURSOR_COUNT INTEGER ALL The number of cursors using CQE for this job. This includes SQL
cursors (both fully opened and pseudo closed) and cursors used
to implement native database queries.
Contains the null value if no cursors have used CQE for this job.

CQE_CURSOR_STORAGE INTEGER ALL The amount of storage, in megabytes, used by cursors using
CQE for this job.
Contains the null value if no cursors have used CQE for this job.

SQE_CURSOR_COUNT INTEGER ALL The number of cursors using SQE for this job. This includes SQL
cursors (both fully opened and pseudo closed) and cursors used
to implement native database queries.
Contains the null value if no cursors have used SQE for this job.

SQE_CURSOR_STORAGE INTEGER ALL The amount of storage, in megabytes, used by cursors using
SQE for this job.
Contains the null value if no cursors have used SQE for this job.

LARGEST_QUERY_SIZE INTEGER ALL The amount of storage, in megabytes, used by the SQE
cursor that used the most storage for this job. This
could be for a different query than the one listed in the
SQL_STATEMENT_TEXT column.
Contains the null value if no cursors have used SQE for this job.

QRO_HASH VARCHAR(8) ALL An internally generated identifier for the SQE query
referred to in the LARGEST_QUERY_SIZE column. This
could be for a different query than the one listed in the
SQL_STATEMENT_TEXT column. The QRO hash surfaces within
Visual Explain and from Show Statements exploration of the
SQL Plan Cache and SQL Plan Cache Snapshots.
Contains the null value if no cursors have used SQE for this job.

OPEN_FILES INTEGER ALL The number of open files (*FILE objects) for this job. For
details about the types of files and their usage, use the
QSYS2.OPEN_FILES table function.

Example
• Example 1: Looking at only QZDASOINIT jobs, find the top 10 consumers of Elapsed I/O.

SELECT JOB_NAME, AUTHORIZATION_NAME, ELAPSED_TOTAL_DISK_IO_COUNT, ELAPSED_CPU_PERCENTAGE


FROM TABLE(QSYS2.ACTIVE_JOB_INFO(
JOB_NAME_FILTER => 'QZDASOINIT',
SUBSYSTEM_LIST_FILTER => 'QUSRWRK')) X
ORDER BY ELAPSED_TOTAL_DISK_IO_COUNT DESC
FETCH FIRST 10 ROWS ONLY;

Database performance and query optimization 1025


Note: The data in the ELAPSED_xxx columns is updated upon each re-execution of the query. Elapsed
data will not get returned the first time a query is run for ACTIVE_JOB_INFO for a connection. See the
reset-statistics parameter for details.
• Example 2: Find the active jobs using the most temporary storage. Include the most recently executed
SQL statement for each target job.

SELECT JOB_NAME, AUTHORIZATION_NAME, TEMPORARY_STORAGE, SQL_STATEMENT_TEXT


FROM TABLE (QSYS2.ACTIVE_JOB_INFO(DETAILED_INFO=>'ALL')) X
WHERE JOB_TYPE <> 'SYS'
ORDER BY TEMPORARY_STORAGE DESC;

ADD_TRACKED_JOB_QUEUE procedure
The ADD_TRACKED_JOB_QUEUE procedure registers a job queue to be tracked by adding it to the tracked
job queue list.
For a subsystem to track jobs, there must be at least one tracked job queue registered to the Submitted
Job Tracker when that subsystem starts.
For more information about the Submitted Job Tracker, see “Submitted Job Tracker” on page 1027.
Authorization: The caller must have *JOBCTL special authority.

ADD_TRACKED_JOB_QUEUE ( iasp-name ,
IASP_NAME =>

job-queue-library ,
JOB_QUEUE_LIBRARY =>

job-queue
JOB_QUEUE =>

, job-retention-period
JOB_RETENTION_PERIOD =>

)
, tracking-file-iasp
TRACKING_FILE_IASP =>

The schema is QSYS2.

iasp-name A character string that contains the name of the ASP where job-queue-library is located.
The ASP does not need to exist. Can contain the following special value:

*SYSBAS The job queue library is located in the system ASP (ASP 1) or any basic user
ASPs (ASPs 2-32).

job-queue- A character string that contains the name of the library containing job-queue. The library
library does not need to exist.
job-queue A character string that contains the name of the job queue to be tracked. A job queue
can be registered even if it does not exist.
Job queues in libraries QSYS and QGPL that start with Q are not eligible to be added.
job-retention- An integer value that specifies the number of minutes job tracking information will be
period retained in the tracking file after the job has ended. The default is 0, which indicates that
the job tracking information is immediately eligible for removal when the job ends.

1026 IBM i: Performance and Query Optimization


Once this time period has elapsed, the job tracking information becomes eligible to be
removed from the job tracking file.
tracking-file- A character string that contains the name of the IASP where the job tracking file for
iasp job-queue is to be created. If a value is provided for this parameter, iasp-name must
have a value of *SYSBAS.
If this parameter is omitted, the job tracking file will be created on the ASP where
job-queue-library is located.

Example
• Add job queue APPLIB/APPJOBQ to the list of tracked job queues.

CALL QSYS2.ADD_TRACKED_JOB_QUEUE(IASP_NAME => '*SYSBAS',


JOB_QUEUE_LIBRARY => 'APPLIB',
JOB_QUEUE => 'APPJOBQ');

Submitted Job Tracker


The Submitted Job Tracker is an IBM i work management feature that tracks the lifecycle of submitted
jobs for a user specified set of jobs queues.
The ADD_TRACKED_JOB_QUEUE procedure registers a job queue to be tracked by adding it to the Job
Queue List (JQL). After a job queue has been registered, any jobs subsequently submitted to that job
queue are tracked in a job tracking file. A user can use the information stored in the job tracking file to
resubmit a job on the original node where the job was tracked or another node. The information in the job
tracking file can help prepare for maintenance, recover from a node failure, or balance workload.
The job tracking file is a database file that keeps track of job submit parameters and job status for any
jobs being tracked by Submitted Job Tracker. The job tracking files is named QSBMJOBTRK/QAMRDJTS3
and can exist in SYSBAS or within an IASP.

Tracking job lifecycle events


To track job lifecycle events, Submitted Job Tracker uses the following work management exit points:
• Change Job (QIBM_QWT_CHGJOB)
• Job Notification (QIBM_QWT_JOBNOTIFY)
• Submit Job (QIBM_QWT_SBMJOB)
See the details for how Submitted Job Tracker handles each lifecycle event below.
Submit Job When a job is submitted to a tracked job queue with SBMJOB, parameters that
(SBMJOB) would be necessary to resubmit the job are stored in the job tracking file.
command
Change Job When a tracked job is changed while it is on a job queue, the job tracking file is
(CHGJOB) updated to reflect the changes.
command or API When a tracked job is changed while it is active, the job tracking file is not updated.
(QWTCHGJB)
If a tracked job is moved from an untracked job queue to one that is not tracked,
then tracking ends for that job and no further updates are made to the job tracking
file. However, the information for that job remains in the job tracking file until the
job queue is no longer tracked or the job tracking file is cleared.
If a job is moved from an untracked job queue to one that is tracked, then the job
remains not tracked.
Note: It is recommended to track all job queues involved in the lifecycle of a
tracked job.

3 For an IASP, the QAMRDJTS job tracking file exists in library QSJTnnnnn.

Database performance and query optimization 1027


Transfer Job Each time an active job is transferred to a tracked job queue, an additional entry is
(TFRJOB) or added to the job tracking file to represent the new routing step associated with that
Transfer Batch job. If the job queue for a routing step is not a tracked job queue, then no additional
Job (TFRBCHJOB) entry for that routing step is added to the job tracking file.
command When the last routing step ends, all entries in the job tracking file for that job are
updated to indicate the job end time. If the job queue for the last routing step is not
a tracked job queue, then the job end time is not updated for any of the entries for
that job in the job tracking file.
Note: It is recommended to track all job queues involved in the lifecycle of a
tracked job.

Job starts When a tracked job starts, the job tracking file is updated to indicate the job start
time.
Job ends When a tracked job ends, the job tracking file is updated to indicate the job end
time and other completion details.
If a job is ended while it is on a tracked job queue that is not allocated to a
subsystem, the job tracking file remains unchanged until the job queue is no longer
tracked or the job tracking file is cleared.
Job schedule Jobs that are scheduled to run at a future date or time using the Add Job
entries Schedule Entry (ADDJOBSCDE) or Work with Job Schedule Entries (WRKJOBSCDE)
commands are not tracked.

The job tracking file is updated asynchronously while tracked jobs encounter lifecycle events. Tracking
information is gathered, processed, and stored in a job tracking file asynchronously by the Submitted Job
Tracker job (QMRDBJNFY). Subsequently, tracking information in the job tracking file will always lag the
real lifecycle event. The lag time should be small in most cases, but it is not zero. This means:
• A job that is queued at the time of a node failure may not appear in the job tracking file.
• A job that has started running at the time of node failure may not appear in the job tracking file or may
be described in the job track file as still queued.
• A job that has ended at the time of node failure may be described in the job tracking file as still queued
or running.

Managing the Submitted Job Tracker


Displaying The list of job queues that have been registered to be tracked is displayed using the
tracked job “TRACKED_JOB_QUEUES view” on page 1135.
queues
Adding Job queues are registered to be tracked using the ADD_TRACKED_JOB_QUEUE
tracked job procedure.
queues
Note: It is recommended to register all job queues allocated to a subsystem before
starting the subsystem.

Removing Job queues are removed from being tracked using the
tracked job “REMOVE_TRACKED_JOB_QUEUE procedure” on page 1090.
queues
Displaying Tracked jobs and their details are displayed using the “TRACKED_JOB_INFO table
tracked jobs function” on page 1126.
Clearing Tracked job information is eligible to be automatically removed from a job tracking
tracked jobs file after the job has ended, the job tracking file has been updated with a job end
details time value, and the job retention period has elapsed. The job retention period is
specified when a job queue is registered with the JQL. The Submitted Job Tracker

1028 IBM i: Performance and Query Optimization


job (QMRDBJNFY) periodically checks for tracked job information that is eligible to be
removed and clears those entries.
All tracked job information for a particular job queue is removed from a job tracking file
when that job queue is removed from the JQL.
There are several situations that may cause Submitted Job Tracker to not receive a
notification that a job has ended and therefore the job end time in the job tracking file
did not get updated. These entries must be manually cleared from the job tracking file.
The following situations can cause a tracked job to get into this state:
• A node has an unplanned outage. When the node is active again, information in the
job tracking file about active jobs when the outage occurred will not have a job end
time value set.
• An IASP is varied off or is unavailable. While the IASP is unavailable, Submitted Job
Tracker is unable to update the job tracking file. When it is varied on again, entries in
the job tracking file may still exist for jobs that have ended but the job end time value
is not set.
• A job is changed or transferred from a tracked job queue to an untracked job queue.
This causes tracking to end for that job but information about it remains in the job
tracking file and the job end time value is not set.
• A user registers a job queue to be tracked by adding it to the JQL after starting the
subsystem where the jobs will run. This can prevent Submitted Job Tracker from
receiving notifications when a job ends, which results in entries in the job tracking
files not being properly updated with job end time values.
• A user submits a job to a tracked job queue and the job is ended before the job queue
is allocated to a subsystem. Submitted Job Tracker does not receive a notification
from work management that the job has ended in this case, therefore the job end
time value is not set for the job in the job tracking file.
• The limit of eight data queues registered for the work management job notification
exit point (QIBM_QWT_JOBNOTIFY) is exceeded. This may cause Submitted Job
Tracker to not receive notifications when a job starts or ends, which results in entries
in the job tracking file not being properly updated.
Tracked job information can be cleared manually using the
“CLEAR_TRACKED_JOB_INFO procedure” on page 1030.

Restoring The JQL, which is a database file named QSYS/QAMRDJQL, can be restored from save
Submitted media. This will replace the existing list of tracked job queues with the list of tracked job
Job Tracker queues from the save media. When the QAMRDJQL file is restored, each job queue on the
data restored list of tracked job queues is ensured to be properly registered with Submitted
Job Tracker. If the restore causes a job queue to no longer be tracked, then the job
tracking file will be cleared of entries for that job queue.
The job tracking file, which is a database file named QSBMJOBTRK/QAMRDJTS4, cannot
be restored from save media. If an attempt is made to restore this system object, it will
not be restored and the existing object is left unchanged. If other objects are included in
the restore request, they will be processed normally.

AUTOSTART_JOB_INFO view
The AUTOSTART_JOB_INFO view returns information about autostart jobs.
The values returned for the columns in the view are closely related to the values returned by the
Display Autostart Job Entries panel accessed through the DSPSBSD (Display Subsystem Description) CL
command and by the List Subsystem Entries (QWDLSBSE) API.

4 For an IASP, the QAMRDJTS job tracking file exists in library QSJTnnnnn.

Database performance and query optimization 1029


Authorization: The caller must have:
• *EXECUTE authority to the library containing the subsystem description, and
• *USE authority to the subsystem description.
The following table describes the columns in the view. The system name is AUTOJ_INFO. The schema is
QSYS2.
Table 263. AUTOSTART_JOB_INFO view

Column Name System Column Name Data Type Description

SUBSYSTEM_DESCRIPTION_LIBRARY SBSD_LIB VARCHAR(10) The name of the library in which the subsystem
description resides.

SUBSYSTEM_DESCRIPTION SBSD VARCHAR(10) The name of the subsystem about which


information is being returned.

AUTOSTART_JOB_NAME AJ_NAME VARCHAR(10) The simple name of the job that is automatically
started when the associated subsystem is started.

JOB_DESCRIPTION_LIBRARY JOBDLIB VARCHAR(10) The name of the library in which the job
description for the autostart job entry resides.

JOB_DESCRIPTION JOBD VARCHAR(10) The name of the job description for the autostart
job entry.

Example
• List all the autostart job entries in the QUSRWRK subsystem.

SELECT AUTOSTART_JOB_NAME, JOB_DESCRIPTION_LIBRARY, JOB_DESCRIPTION


FROM QSYS2.AUTOSTART_JOB_INFO
WHERE SUBSYSTEM_DESCRIPTION_LIBRARY = 'QSYS' AND
SUBSYSTEM_DESCRIPTION = 'QSYSWRK'
ORDER BY 1, 2, 3;

CLEAR_TRACKED_JOB_INFO procedure
The CLEAR_TRACKED_JOB_INFO procedure removes entries from the job tracking file that exists on the
specified ASP group.
Many filters are provided to restrict the entries that are removed from job tracking files by this procedure.
The filters are additive, with each one further limiting the entries to be removed. If none of the filter
parameters are specified, all entries are removed from the job tracking file.
Authorization: The caller must have *JOBCTL special authority.

1030 IBM i: Performance and Query Optimization


CLEAR_TRACKED_JOB_INFO ( iasp-name
IASP_NAME =>

, node-name
NODE_NAME =>

, job-queue-library
JOB_QUEUE_LIBRARY =>

, job-queue
JOB_QUEUE =>

, internal-job-identifier
INTERNAL_JOB_IDENTIFIER =>

)
, routing-step
ROUTING_STEP =>

The schema is QSYS2.

iasp-name A character string that contains the name of the IASP where the job tracking file to be
cleared is located. Can contain the following special value:

*SYSBAS The job tracking file is located in the system ASP (ASP 1) or any basic user
ASPs (ASPs 2-32).

node-name A character string that contains a node name. Entries in a job tracking file for this node are
removed. Can contain the following special value:

*LOCAL The node where the procedure is being run is used.

If this parameter is omitted, the node name is not used to limit entries to be removed.
job-queue- A character string that contains a job queue library name. Entries in a job tracking file for a
library job queue in this library are removed.
If this parameter is omitted, the job queue library name is not used to limit entries to be
removed.
job-queue A character string that contains a job queue name. Entries in a job tracking file for a job
queue with this name are removed.
If this parameter is omitted, the job queue name is not used to limit entries to be
removed.
internal- A binary string that contains an internal job identifier. Entries in a job tracking file with this
job- internal job identifier on node-name are removed.
identifier When internal-job-identifier is specified, node-name must be specified. job-queue-library
and job-queue must not be specified.
If this parameter is omitted, the internal job identifier is not used to limit entries to be
removed.
routing-step An integer that contains a routing step number. Entries in a job tracking file with this
routing step and internal-job-identifier on node-name are removed.

Database performance and query optimization 1031


When routing-step is specified, internal-job-identifier and node-name must be specified.
job-queue-library and job-queue must not be specified.
If this parameter is omitted, the routing step number is not used to limit entries to be
removed.

Examples
• Clear all tracked job information from the job tracking file in *SYSBAS.

CALL QSYS2.CLEAR_TRACKED_JOB_INFO(IASP_NAME => '*SYSBAS');

• Clear tracked job information for all jobs submitted to any job queue in library MYLIB on any node.

CALL QSYS2.CLEAR_TRACKED_JOB_INFO(IASP_NAME => '*SYSBAS',


JOB_QUEUE_LIBRARY => 'MYLIB');

• Clear tracked job information for all jobs submitted to any job queue named MYJOBQ in any library on
any node.

CALL QSYS2.CLEAR_TRACKED_JOB_INFO(IASP_NAME => '*SYSBAS',


JOB_QUEUE => 'MYJOBQ');

• Clear tracked job information for all jobs submitted to job queue MYJOBQ in library MYLIB on the local
node.

CALL QSYS2.CLEAR_TRACKED_JOB_INFO(IASP_NAME => '*SYSBAS',


NODE_NAME => '*LOCAL',
JOB_QUEUE_LIBRARY => 'MYLIB',
JOB_QUEUE => 'MYJOBQ');

• Clear tracked job information for a specific job on the local node.

CALL QSYS2.CLEAR_TRACKED_JOB_INFO(IASP_NAME => '*SYSBAS',


NODE_NAME => '*LOCAL',
INTERNAL_JOB_IDENTIFIER => BX'0000000100142F00AAE4AE8F89E30001');

• Clear tracked job information for routing step 2 of a specific job on the local node.

CALL QSYS2.CLEAR_TRACKED_JOB_INFO(IASP_NAME => '*SYSBAS',


NODE_NAME => '*LOCAL',
INTERNAL_JOB_IDENTIFIER => BX'0000000100142F00AAE4AE8F89E30001',
ROUTING_STEP => 2);

COMMUNICATIONS_ENTRY_INFO view
The COMMUNICATIONS_ENTRY_INFO view returns information about subsystem communications
entries.
The values returned for the columns in the view are closely related to the values returned by the
Display Communications Entries and Display Remote Location Name Entries panels accessed through the
DSPSBSD (Display Subsystem Description) CL command and by the List Subsystem Entries (QWDLSBSE)
API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the subsystem description, and
• *USE authority to the subsystem description.
The following table describes the columns in the view. The system name is COMM_INFO. The schema is
QSYS2.

1032 IBM i: Performance and Query Optimization


Table 264. COMMUNICATIONS_ENTRY_INFO view

Column Name System Column Name Data Type Description

SUBSYSTEM_DESCRIPTION_LIBRARY SBSD_LIB VARCHAR(10) The name of the library in which the subsystem
description resides.

SUBSYSTEM_DESCRIPTION SBSD VARCHAR(10) The name of the subsystem about which


information is being returned.

DEVICE DEVICE VARCHAR(10) The name of the device description or the type of
the device being used with this communications
Nullable entry. Can contain the following special values:

*ALL All communications device types


are used with this communications
entry.

*APPC All advanced program-to-program


communications devices can be
used with this communications
entry.

*ASYNC All asynchronous communications


devices can be used with this
communications entry.

*BSCEL All bisynchronous equivalency link


communications devices can be
used with this communications
entry.

*FINANCE All finance communications


devices can be used with this
communications entry.

*INTRA All intrasystem communications


devices can be used with this
communications entry.

*RETAIL All retail communications devices


can be used with this
communications entry.

*SNUF All SNA upline facility


communications devices can be
used with this communications
entry.

Contains the null value if this entry was defined


using a remote location name.

REMOTE_LOCATION RMT_LOC VARCHAR(8) The name of the remote location for this entry.

Nullable Contains the null value if this entry was defined


using a device description name.

MODE MODE VARCHAR(8) The mode name of the communications device.


Can contain the following special value:

*ANY Any available modes defined to the


communications device are allocated to
the subsystem. If the communications
device does not have defined modes
associated with it, the communications
device itself is allocated to the
subsystem.

JOB_DESCRIPTION_LIBRARY JOBDLIB VARCHAR(10) The name of the library in which the


communications entry job description resides.
Nullable
Contains the null value if JOB_DESCRIPTION is
*USRPRF.

Database performance and query optimization 1033


Table 264. COMMUNICATIONS_ENTRY_INFO view (continued)

Column Name System Column Name Data Type Description

JOB_DESCRIPTION JOBD VARCHAR(10) The name of the job description used when
a job is started as a result of receiving a
program start request and processed through this
communications entry. Can contain the following
special value:

*USRPRF The job description name that is


specified in the user profile of
the user that made the program
start request is used for jobs
that are processed through this
communications entry.

DEFAULT_USER DFT_USER VARCHAR(10) The name of the default user profile used for
evoke requests that enter the subsystem through
Nullable this entry and contain no security information.
Can contain the following special value:

*SYS All user program start requests are


treated the same as if no user profile
is specified as the default. For program
start requests that are sent by system
functions, the request runs under a
predetermined user profile if a user
profile is not specified on the program
start request.

Contains the null value if no user profile is


specified as the default.

MAXIMUM_ACTIVE_JOBS MAX_ACTIVE INTEGER The maximum number of jobs that can be active
at the same time through this entry.
Nullable
Contains the null value if the entry specifies
*NOMAX, indicating that there is no maximum.

Example
• List all the communications entries defined for the QCMN subsystem.

SELECT *
FROM QSYS2.COMMUNICATIONS_ENTRY_INFO
WHERE SUBSYSTEM_DESCRIPTION_LIBRARY = 'QSYS' AND
SUBSYSTEM_DESCRIPTION = 'QCMN';

ENDED_JOB_INFO table function


The ENDED_JOB_INFO table function returns information about jobs that have ended. This information is
gathered from CPF1164 messages recorded in the history log.
Authorization: See Note below.

ENDED_JOB_INFO (
start-time
START_TIME =>

)
, end-time
END_TIME =>

The schema is SYSTOOLS.

start-time A timestamp expression that indicates the starting timestamp to use for returning ended job
information.
If this parameter is omitted, the default of CURRENT DATE - 1 DAY is used.

1034 IBM i: Performance and Query Optimization


end-time A timestamp expression that indicates the ending timestamp to use for returning ended job
information.
If this parameter is omitted, the default of '9999-12-30-00.00.00.000000' is used.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 265. ENDED_JOB_INFO table function

Column Name Data Type Description

MESSAGE_TIMESTAMP TIMESTAMP The timestamp when the CPF1164 message was sent.

FROM_USER VARCHAR(10) The user name of the job from which the CPF1164 message was sent.

FROM_JOB VARCHAR(28) The qualified job name from which the CPF1164 message was sent.

FROM_JOB_NAME VARCHAR(10) The name of the job from which the CPF1164 message was sent.

FROM_JOB_USER VARCHAR(10) The user profile that started the job from which the CPF1164
message was sent.

FROM_JOB_NUMBER VARCHAR(6) The job number of the job from which the CPF1164 message was
sent.

JOB_INTERFACE VARCHAR(22) The interface used by the job reported by the CPF1164 message.
• CENTRAL SERVER
• CLI DB CONNECTION
• DATA QUEUE SERVER
• DB2 MIRROR
• DRDA DDM SERVER TCP/IP
• FILE SERVER
• FTP
• NETSERVER FILE SHARE
• ODBC OR FILE TXFR
• OTHER
• PRINT SERVER
• REMOTE COMMAND
• REXEC
• SIGNON SERVER
• SNDNETXXX
• SSH CONNECTION
• TELNET/5250

FROM_PROGRAM VARCHAR(10) The program that sent the CPF1164 message.

CPU_TIME DECIMAL(15,3) The total amount of processing used by the job, in seconds.

NUMBER_OF_STEPS SMALLINT The number of routing steps used by the job.

JOB_END_CODE SMALLINT The job end code.

0 The job completed normally

10 The job completed normally during controlled ending or


controlled subsystem ending

20 The job exceeded end severity (ENDSEV job attribute)

30 The job ended abnormally

40 The job ended before becoming active

50 The job ended while the job was active

60 The subsystem ended abnormally while the job was active

70 The system ended abnormally while the job was active

80 The job ended (ENDJOBABN command)

90 The job was forced to end after the time limit ended
(ENDJOBABN command)

Database performance and query optimization 1035


Table 265. ENDED_JOB_INFO table function (continued)

Column Name Data Type Description

JOB_END_DETAIL VARCHAR(100) Descriptive text corresponding to JOB_END_CODE.

SECONDARY_ENDING_CODE SMALLINT The job's secondary ending code.

0 No secondary ending code

100 Disconnect time interval exceeded

101 Session device deleted

102 Error calling Disconnect Job (DSCJOB)

300 Device error and DEVRCYACN set to *ENDJOB

301 Job ended due to looping on device errors

SECONDARY_ENDING_CODE_DETAIL VARCHAR(100) Descriptive text corresponding to SECONDARY_ENDING_CODE.

JOB_ENTERED_SYSTEM_TIME TIMESTAMP(0) The time the job entered the system.


Returns the null value if the value is not available.

JOB_ACTIVE_TIME TIMESTAMP(0) The time the job started to run.


Returns the null value if the value is not available.

TOTAL_RESPONSE_TIME INTEGER The total response time for an interactive job.

SUBSYSTEM VARCHAR(10) Subsystem where the job was run.

INTERACTIVE_TRANSACTIONS INTEGER The total number of operator interactions, such as pressing the Enter
key, for the job.

SYNC_AUX_IO_COUNT INTEGER The number of synchronous (physical) disk I/O operations performed
by the job. This value is the sum of the synchronous database and
non-database reads and writes.

JOB_TYPE VARCHAR(11) The type of job.

AUTOSTART The job is an autostart job.

BATCH The job is a batch job.

INTERACTIVE The job is an interactive job.

MONITOR The job is a subsystem monitor job.

READER The job is a spooled reader job.

SCPF The job is the SCPF system job.

SYSTEM The job is a system job.

WRITER The job is a spooled writer job.

PEAK_TEMPORARY_STORAGE INTEGER The maximum temporary storage, in megabytes, used by the job.

Note
This function is provided in the SYSTOOLS schema as an example of how to extract information from
message substitution variables. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL source
can be extracted and used as a model for building similar helper functions, or to create a customized
version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
List the 10 jobs from yesterday and today that were the top consumers of temporary storage.

SELECT FROM_USER, FROM_JOB, PEAK_TEMPORARY_STORAGE, JOB_ACTIVE_TIME


FROM TABLE (SYSTOOLS.ENDED_JOB_INFO() )
ORDER BY PEAK_TEMPORARY_STORAGE DESC
LIMIT 10;

1036 IBM i: Performance and Query Optimization


GET_JOB_INFO table function
The GET_JOB_INFO table function returns one row containing the information about a specific job.
Authorization: None required for a job where the caller's user profile is the same as the job user identity
of the job for which the information is being returned.
Otherwise, the caller must have either *JOBCTL special authority, or be authorized to the
QIBM_DB_SQLADM or QIBM_DB_SYSMON function usage identifiers.

GET_JOB_INFO ( job-name
V_JOB_NAME =>

)
, ignore-errors
V_IGNORE_ERRORS =>

The schema is QSYS2.

job-name A character or graphic string expression that identifies the name of a job. Two forms of a job
name are supported.
1. A fully qualified job name in the form job-number/job-user/job-name.
2. The first 10 characters are the job name, the second 10 characters are the user name,
and the last 6 characters are the job number.
The special value of '*' indicates the current job.
ignore- A character or graphic string expression that identifies what to do when an error is
errors encountered.

NO An error is returned. This is the default.

YES A warning is returned. No row is returned when an error is encountered.

The result of the function is a table containing a single row with the format shown in the following table.
All the columns are nullable.
Table 266. GET_JOB_INFO table function

Column Name Data Type Description

V_JOB_STATUS CHAR(10) Status of the job.

*ACTIVE Job is active. It could be a group job, system request job, or


disconnected job.

*JOBQ Job is currently on job queue.

*OUTQ Job has completed running but has output on an output queue or
the job log has not yet been written.

V_ACTIVE_JOB _STATUS CHAR(4) The active status of the initial thread of the job.
For the list of values see Work Management API Attribute Descriptions in
Application Programming Interfaces and search on "Active job status".
Returns null if the job is in transition or is not active.

Database performance and query optimization 1037


Table 266. GET_JOB_INFO table function (continued)

Column Name Data Type Description

V_ACTIVE_JOB_TYPE VARCHAR(3) Type of active job.

ASJ Autostart

BCH Batch

BCI Batch Immediate

EVK Started by a procedure start request

INT Interactive

M36 Advanced 36 server job

MRT Multiple requester terminal

PDJ Print driver job

PJ Prestart job

RDR Spool reader

SBS Subsystem monitor

SYS System

WTR Spool writer

Returns null if the job type is not available for jobs that are no longer active.

V_RUN_PRIORITY INTEGER The priority at which the job competes for the processing unit relative to other
jobs that are active at the same time. The run priority ranges from 1 (highest
priority) to 99 (lowest priority).

V_AUTHORIZATION_NAME VARCHAR(10) The user profile under which the initial thread is running at this time. For jobs
that swap user profiles, this user profile name and the user profile that initiated
the job can be different.

V_SBS_NAME CHAR(10) Name of subsystem where job is running.


Returns null if the job is not active.

V_CPU_USED BIGINT The amount of CPU time (in milliseconds) that has been currently used by this
job.

V_TEMP_STORAGE_USED_MB INTEGER The amount of auxiliary storage (in megabytes) that is currently allocated to this
job.

V_AUX_IO_REQUESTED BIGINT The number of auxiliary I/O requests performed by the job across all routing
steps. This includes both database and nondatabase paging.

V_PAGE_FAULTS BIGINT The number of times an active program referenced an address that was not in
main storage during the current routing step of the specified job.

V_CLIENT_WRKSTNNAME CHAR(255) Value of the SQL CLIENT_WRKSTNNAME special register.


Returns null if the job is not active.

V_CLIENT_APPLNAME CHAR(255) Value of the SQL CLIENT_APPLNAME special register.


Returns null if the job is not active.

V_CLIENT_ACCTNG CHAR(255) Value of the SQL CLIENT_ACCTNG special register.


Returns null if the job is not active.

V_CLIENT_PROGRAMID CHAR(255) Value of the SQL CLIENT_PROGRAMID special register.


Returns null if the job is not active.

V_CLIENT_USERID CHAR(255) Value of the SQL CLIENT_USERID special register.


Returns null if the job is not active.

V_SQL_STATEMENT_TEXT VARCHAR(10000) Statement text of the last SQL statement to run or the SQL statement that is
currently running.
Returns null if the job is not active.

1038 IBM i: Performance and Query Optimization


Table 266. GET_JOB_INFO table function (continued)

Column Name Data Type Description

V_SQL_STMT_STATUS CHAR(8) The status of SQL within this job.

ACTIVE An SQL statement is currently running

COMPLETE At least one SQL statement has run and has completed

UNKNOWN The SQL status is not known

Returns null if no SQL statement has been run.

V_SQL_STMT_START_TIMESTAMP TIMESTAMP The timestamp of the execution start for an active SQL statement. If there is no
active SQL statement, the null value is returned.

V_QUERY_OPTIONS_LIB_NAME CHAR(10) The name of the QAQQINI options library in use for this job.

V_CLIENT_IP_ADDRESS VARCHAR(45) Client IP address being used by the job.


Returns null when no client IP address exists or the job is using IPv6.

V_PJ_REUSE_COUNT INTEGER The number of times the prestart job has been used. The prestart job reuse
count is incremented when a disconnect is processed for a prestart job. When
the prestart job reuse count exceeds the prestart job maximum number of uses,
the job is ended.
Returns null if the job is not active or if the job is not a prestart job.

V_PJ_MAXUSE_COUNT INTEGER The maximum number of times the prestart job can be used before it is ended. A
value of -1 is returned for *NOMAX.
Returns null if the job is not active or if the job is not a prestart job.

Example
Return information about job 347117/QUSER/QZDASOINIT.

SELECT * FROM TABLE(QSYS2.GET_JOB_INFO('347117/QUSER/QZDASOINIT'));

JOB_DESCRIPTION_INFO view
The JOB_DESCRIPTION_INFO view returns information about job descriptions.
The values returned for the columns in the view are closely related to the values returned by the Display
Job Description (DSPJOBD) CL command and the Retrieve Job Description Information (QWDRJOBD) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the job description, and
• *OBJOPR and *READ authorities to the job description.
The following table describes the columns in the view. The system name is JOBD_INFO. The schema is
QSYS2.
Table 267. JOB_DESCRIPTION_INFO view

Column Name System Column Name Data Type Description

JOB_DESCRIPTION_LIBRARY JOBDLIB VARCHAR(10) The name of the library in which the job description resides.

JOB_DESCRIPTION JOBD VARCHAR(10) The name of the job description about which information is being
returned.

AUTHORIZATION_NAME USER_NAME VARCHAR(10) The name of the user profile associated with this job description.
Can contain the following special value:

*RQD A user name is required to use the job description.

JOB_DATE JOB_DATE DATE The date that will be assigned to jobs using this job description
Nullable when they are started.
Contains the null value if this job will use the QDATE system
value.

Database performance and query optimization 1039


Table 267. JOB_DESCRIPTION_INFO view (continued)

Column Name System Column Name Data Type Description

ACCOUNTING_CODE ACGCDE VARCHAR(15) An identifier assigned to jobs that use this job description. This
code is used to collect system resource use information. Can
contain the following special value:

*USRPRF The accounting code used for jobs using this job
description is obtained from the job's user profile.

ROUTING_DATA RTGDTA VARCHAR(80) The routing data that is used with this job description to start
jobs. Can contain one of the following special values:

QCMDI The default routing data QCMDI is used by


the IBM-supplied interactive subsystem to route
the job to the IBM-supplied control language
processor QCMD in the QSYS library.

*RQSDTA Up to the first 80 characters of the request data


specified in the request data field are used as the
routing data for the job.

REQUEST_DATA RQSDTA VARCHAR(256) The request data that is placed as the last entry in the job's
Nullable message queue for jobs that use this job description. Can
contain the following special value:

*RTGDTA The data specified in the routing data parameter


is placed as the last entry in the job's message
queue.

Contains the null value if no request data is placed in the job's


message queue.

LIBRARY_LIST_COUNT LIBL_COUNT INTEGER The number of libraries in the user portion of the initial library
list.

LIBRARY_LIST LIBL VARCHAR(2750) The initial library list that is used for jobs that use this job
Nullable description. Only the libraries in the user portion of the library
list are included. The list is an array of 11 character entries. Each
entry contains a ten character name followed by one blank. Can
contain the following special value:

*SYSVAL The jobs using this job description will use the
library list specified by the QUSRLIBL system value.

Contains the null value is there is no initial library list.

JOB_SWITCHES SWITCHES CHAR(8) The initial settings for a group of eight job switches used by jobs
that use this job description. These switches can be set or tested
in a program and used to control a program's flow. The possible
values are '0' (off) and '1' (on).

TEXT_DESCRIPTION TEXT VARCHAR(50) The user text, if any, used to briefly describe the job description.
Nullable Contains the null value is there is no descriptive text.

JOB_QUEUE_LIBRARY JOBQLIB VARCHAR(10) The library of the job queue into which batch jobs using this job
description are placed.

JOB_QUEUE JOBQ VARCHAR(10) The name of the job queue into which batch jobs using this job
description are placed.

JOB_QUEUE_PRIORITY JOBQ_PRI SMALLINT The scheduling priority of each job that uses this job description.
The highest priority is 1 and the lowest priority is 9.

HOLD_ON_JOB_QUEUE JOBQ_HOLD VARCHAR(4) Whether jobs using this job description are put on the job queue
with a status of held.

*NO Jobs using this job description are not put on the job
queue as held.

*YES Jobs using this job description are put on the job queue
as held.

OUTPUT_QUEUE_LIBRARY OUTQLIB VARCHAR(10) The name of the library in which the output queue resides.
Nullable Contains the null value if OUTPUT_QUEUE is a special value.

1040 IBM i: Performance and Query Optimization


Table 267. JOB_DESCRIPTION_INFO view (continued)

Column Name System Column Name Data Type Description

OUTPUT_QUEUE OUTQ VARCHAR(10) The name of the default output queue that is used for spooled
output produced by jobs that use this job description. Can
contain one of the following special values:

*DEV The output queue with the same name as the


printer device for this job description is used.

*USRPRF The output queue name for jobs using this job
description is obtained from the user profile of the
job at the time the job is started.

*WRKSTN The output queue name is obtained from the


device description from which this job is started.

OUTPUT_QUEUE_PRIORITY OUTQ_PRI SMALLINT The output priority for spooled files that are produced by jobs
using this job description. The highest priority is 1, and the
lowest priority is 9.

SPOOLED_FILE_ACTION SPOOL_ACT VARCHAR(7) Specifies whether spooled files can be accessed through job
interfaces once a job has completed its normal activity.

*DETACH Spooled files are detached from the job when the
job completes its activity.

*KEEP When the job completes its activity, as long as


at least one spooled file for the job exists in
the system auxiliary storage pool (ASP 1) or in
a basic user ASP (ASPs 2-32), the spooled files
are kept with the job and the status of the job is
updated to indicate that the job has completed.
If all remaining spooled files for the job are in
independent ASPs (ASPs 33-255), the spooled
files will be detached from the job and the job will
be removed from the system.

*SYSVAL The jobs using this job description will take the
spooled file action specified by the QSPLFACN
system value.

PRINTER_DEVICE DEV_NAME VARCHAR(10) The name of the printer device that is used for all spooled files
created by jobs that use this job description. Can contain one of
the following special values:

*SYSVAL The value in the system value QPRTDEV at the


time the job is started is used as the printer
device name.

*USRPRF The printer device name is obtained from the user


profile of the job at the time the job is started.

*WRKSTN The printer device name is obtained from the


work station where the job was started.

PRINT_TEXT PRINT_TEXT VARCHAR(30) The line of text that is printed at the bottom of each page of
Nullable printed output for jobs using this job description. Can contain the
following special value:

*SYSVAL The value in the system value QPRTTXT is used for


jobs using this job description.

Contains the null value if there is no text to print.

JOB_MESSAGE_QUEUE MSGQ_MAX SMALLINT The maximum size (in megabytes) of the job message queue.
_MAXIMUM_SIZE Nullable The possible values are 2 to 64.
Contains the null value if the maximum size is set by system
value QJOBMSGQMX at the time the job is started.

Database performance and query optimization 1041


Table 267. JOB_DESCRIPTION_INFO view (continued)

Column Name System Column Name Data Type Description

JOB_MESSAGE_QUEUE_FULL MSGQ_FULL VARCHAR(8) The action taken when the job message queue becomes full.
_ACTION
*NOWRAP When the message queue becomes full, do not
wrap. This action will cause the job to end.

*PRTWRAP When the message queue becomes full, wrap


the job queue and print the messages that are
being overlaid.

*SYSVAL The value is specified by the system value


QJOBMSGQFL.

*WRAP When the message queue becomes full, wrap to


the beginning and start filling again.

SYNTAX_CHECK_SEVERITY SYNTAX SMALLINT Whether requests placed on the job's message queue are
Nullable checked for syntax as CL commands, and the message severity
that causes a syntax error to end processing of a job. The
possible values are:

0-99 Specifies the lowest message severity that causes a


running job to end. The request data is checked for
syntax as CL commands, and, if a syntax error occurs
that is greater than or equal to the error message
severity specified here, the running of the job that
contains the erroneous command is suppressed.

Contains the null value if the request data is not checked for
syntax as CL commands. This is equivalent to *NOCHK.

JOB_END_SEVERITY JOB_ENDSEV SMALLINT The message severity level of escape messages that can cause a
batch job to end. The batch job ends when a request in the batch
input stream sends an escape message whose severity is equal
to or greater than this value to the request processing program.
The possible values are from 0 through 99.

JOBLOG_OUTPUT JOBLOG_OUT VARCHAR(10) How the job log will be produced when the job completes. This
does not affect job logs produced when the message queue is
full and the job message queue full action specifies *PRTWRAP.
Messages in the job message queue are written to a spooled file,
from which the job log can be printed, unless the Control Job Log
Output (QMHCTLJL) API was used in the job to specify that the
messages in the job log are to be written to a database file.
The job log output value can be changed at any time until the
job log has been produced or removed. To change the job log
output value for a job, use the Change Job (QWTCHGJB) API or
the Change Job (CHGJOB) command.
The job log can be displayed at any time until the job log has
been produced or removed. To display the job log, use the
Display Job Log (DSPJOBLOG) command.
The job log can be removed when the job has completed and the
job log has not yet been produced or removed. To remove the job
log, use the Remove Pending Job Log (QWTRMVJL) API or the
End Job (ENDJOB) command.
The possible values are:

*JOBEND The job log will be produced by the job itself.


If the job cannot produce its own job log, the
job log will be produced by a job log server.
For example, a job does not produce its own
job log when the system is processing a Power
Down System (PWRDWNSYS) command.

*JOBLOGSVR The job log will be produced by a job log


server. For more information about job log
servers, refer to the Start Job Log Server
(STRLOGSVR) command.

*PND The job log will not be produced. The job log
remains pending until removed.

*SYSVAL The value is specified by the QLOGOUTPUT


system value.

1042 IBM i: Performance and Query Optimization


Table 267. JOB_DESCRIPTION_INFO view (continued)

Column Name System Column Name Data Type Description

INQUIRY_MESSAGE_REPLY INQ_REPLY VARCHAR(8) How inquiry messages are answered for jobs that use this job
description.

*DFT The system uses the default message reply to


answer any inquiry messages issued while the job
is running. The default reply is either defined in
the message description or is the default system
reply.

*RQD The job requires an answer for any inquiry


messages that occur while the job is running.

*SYSRPYL The system reply list is checked to see if there is


an entry for an inquiry message issued while the
job is running. If a match occurs, the system uses
the reply value for that entry. If no entry exists
for that message, the system uses an inquiry
message.

MESSAGE_LOGGING_LEVEL LOG_LEVEL SMALLINT The type of information logged.

0 No messages are logged.

1 All messages sent to the job's external message queue with


a severity greater than or equal to the message logging
severity are logged. This includes the indication of job start,
job end, and job completion status.

2 The following information is logged:


• Level 1 information.
• Request messages that result in a high-level message
with a severity code greater than or equal to the logging
severity cause the request message and all associated
messages to be logged.
Note: A high-level message is one that is sent to the
program message queue of the program that receives
the request message. For example, QCMD is an IBM-
supplied request processing program that receives
request messages.

3 The following information is logged:


• Level 1 and 2 information.
• All request messages.
• Commands run by a CL program are logged if it is
allowed by the logging of CL programs job attribute and
the log attribute of the CL program.

4 The following information is logged:


• All request messages and all messages with a severity
greater than or equal to the message logging severity,
including trace messages.
• Commands run by a CL program are logged if it is
allowed by the logging of CL programs job attribute and
the log attribute of the CL program.

MESSAGE_LOGGING_SEVERITY LOG_SEV SMALLINT The severity level that is used in conjunction with the logging
level to determine which error messages are logged in the job
log. The possible values are from 0 through 99.

MESSAGE_LOGGING_TEXT LOG_TEXT VARCHAR(7) The level of message text that is written in the job log when
a message is logged according to the logging level and logging
severity.

*MSG Only the message text is written to the job log.

*NOLIST If the job ends normally, no job log is produced. If


the job ends abnormally (if the job end code is 20
or higher), a job log is produced. The messages that
appear in the job log contain both the message text
and the message help.

*SECLVL Both the message text and the message help


(cause and recovery) of the error message are
written to the job log.

Database performance and query optimization 1043


Table 267. JOB_DESCRIPTION_INFO view (continued)

Column Name System Column Name Data Type Description

LOG_CL_PROGRAM_COMMANDS LOG_CL VARCHAR(4) Whether or not commands are logged for CL programs that are
run.

*NO CL programs are not logged.

*YES CL programs are logged.

DEVICE_RECOVERY_ACTION DEVRECOVER VARCHAR(13) The action to take when an I/O error occurs for the interactive
job's requesting program device.

*DSCENDRQS Disconnects the job when an I/O error


occurs. When the job reconnects, the
system sends the End Request (ENDRQS)
command to return control to the previous
request level.

*DSCMSG Disconnects the job when an I/O


error occurs. When the job reconnects,
the system sends a message to the
application program indicating the job
has reconnected and that the workstation
device has recovered.

*ENDJOB Ends the job when an I/O error occurs. A


message is sent to the job's log and to the
history log (QHST). This message indicates
that the job ended because of a device
error.

*ENDJOBNOLIST Ends the job when an I/O error occurs.


There is no job log produced for the
job. The system sends a message to the
history log (QHST). This message indicates
that the job ended because of a device
error.

*MSG Signals the I/O error message to the


application and lets the application
program perform error recovery.

*SYSVAL The value in the system value


QDEVRCYACN at the time the job is started
is used as the device recovery action for
this job description.

TIME_SLICE_END_POOL TIME_SLICE VARCHAR(7) Whether interactive jobs using this job description should be
moved to another main storage pool when they reach time-slice
end.

*BASE The job is moved to the base pool when it reaches


time-slice end.

*NONE The job is not moved when it reaches time-slice


end.

*SYSVAL The system value is used.

ALLOW_MULTIPLE_THREADS ALWMLTTHD VARCHAR(4) Whether or not the job is allowed to run with multiple user
threads. This attribute does not prevent the operating system
from creating system threads in the job. This attribute is not
allowed to be changed once a job starts. This attribute applies
to autostart jobs, prestart jobs, batch jobs submitted from job
schedule entries, and jobs started by using the Submit Job
(SBMJOB) and Batch Job (BCHJOB) commands. This attribute
is ignored when starting all other types of jobs. This attribute
should be set to *YES only in job descriptions that are used
exclusively with functions that create multiple user threads.

*NO The job is not allowed to run with multiple user


threads.

*YES The job is allowed to run with multiple user threads.

1044 IBM i: Performance and Query Optimization


Table 267. JOB_DESCRIPTION_INFO view (continued)

Column Name System Column Name Data Type Description

WORKLOAD_GROUP WRK_GROUP VARCHAR(10) The name of the workload group that is used for jobs that use
Nullable this job description. Can contain the following special value:

*SBSD The workload group named in the subsystem


description is used.

Contains the null value if jobs using this job description do not
have a defined workload group.

ASPGRP ASPGRP VARCHAR(10) The name of the ASP group. This is the name of the primary
Nullable ASP device in an ASP group or the name of an ASP device
description. This specifies the initial ASP group setting for jobs
using this job description.
Contains the null value if jobs using this job description do not
have an initial ASP group.

DDM_CONVERSATION DDM_CONV VARCHAR(5) Whether the Distributed Data Management conversations are
kept or dropped when they are not being used. The possible
values are:

*DROP The system ends a DDM-allocated conversation when


there are no users.

*KEEP The system keeps DDM conversation connections


active when there are no users.

Examples
• Review information about the job queues associated with each job description.

SELECT JOB_DESCRIPTION_LIBRARY, JOB_DESCRIPTION,


JOB_QUEUE_LIBRARY, JOB_QUEUE, JOB_QUEUE_PRIORITY
FROM QSYS2.JOB_DESCRIPTION_INFO;

• Find the job descriptions that have APPLIB1 in their library list

SELECT JOB_DESCRIPTION_LIBRARY, JOB_DESCRIPTION, LIBRARY_LIST


FROM QSYS2.JOB_DESCRIPTION_INFO
WHERE LIBRARY_LIST LIKE '%APPLIB1%';

• Examine the library lists for every job description.


Since the library list column returns a character string containing a list of libraries, to see the individual
library names it needs to be broken apart. To do this, you can create a table function that takes the
library list string and returns a list of library names.

CREATE OR REPLACE FUNCTION QGPL.GET_LIB_NAMES(JOBD_LIBL VARCHAR(2750),


JOBD_LIBL_CNT INT)
RETURNS TABLE(LIBL_POSITION INT, LIBRARY_NAME VARCHAR(10))
BEGIN
DECLARE IN_POS INT;
DECLARE LIB_CNT INT;
SET IN_POS = 1;
SET LIB_CNT = 1;
WHILE LIB_CNT <= JOBD_LIBL_CNT
DO
PIPE (LIB_CNT, RTRIM((SUBSTR(JOBD_LIBL, IN_POS, 10))));
SET IN_POS = IN_POS + 11;
SET LIB_CNT = LIB_CNT + 1;
END WHILE;
RETURN;
END;

Now this function can be used to return the list of library names.

SELECT JOB_DESCRIPTION, JOB_DESCRIPTION_LIBRARY, LIBL_POSITION, LIBRARY_NAME


FROM QSYS2.JOB_DESCRIPTION_INFO,
TABLE (QGPL.GET_LIB_NAMES(LIBRARY_LIST, LIBRARY_LIST_COUNT)) X;

Database performance and query optimization 1045


JOB_INFO table function
The JOB_INFO table function returns one row for each job meeting the selection criteria.
It returns information similar to what is returned by the Work with User Jobs (WRKUSRJOB), Work with
Subsystem Jobs (WRKSBSJOB), and Work with Submitted Jobs (WRKSBMJOB) CL commands and the List
Job (QUSLJOB) API.
Authorization: None required.

JOB_INFO (
job-status-filter
JOB_STATUS_FILTER =>

, job-type-filter
JOB_TYPE_FILTER =>

, job-subsystem-filter
JOB_SUBSYSTEM_FILTER =>

, job-user-filter
JOB_USER_FILTER =>

)
, job-submitter-filter
JOB_SUBMITTER_FILTER =>

The schema is QSYS2.

job-status- A character or graphic string expression that specifies the value to use as the job status
filter filtering criteria. The string must be one of the following special values:

*ALL Jobs of any status including jobs on job queues, active jobs, and jobs on an
output queue.
*ACTIVE Jobs that are active. You can use the QSYS2.ACTIVE_JOB_INFO table
function to get additional details for these jobs.
*JOBQ Jobs that are not active because they are waiting on a job queue.
*OUTQ Jobs that have completed execution and have output on an output queue.

If this parameter is not provided, a value of *ALL is used.

job-type-filter A character or graphic string expression that specifies the value to use as the job type
filtering criteria. The string must be one of the following special values:

*ALL All types of user jobs, including interactive jobs and batch jobs.
*BATCH Only batch user jobs, including prestart jobs, batch immediate jobs, and
autostart jobs.
*INTERACT Only interactive user jobs.

If this parameter is not provided, a value of *ALL is used.

1046 IBM i: Performance and Query Optimization


job- A character or graphic string expression that specifies the subsystem value to use as
subsystem- the job subsystem filtering criteria. The string can be a subsystem name or the following
filter value:

*ALL All jobs in all subsystems, including jobs that are on job queues and on output
queues.

If a subsystem name is provided, only active jobs are found.


If this parameter is not provided, a value of *ALL is used.

job-user-filter The USER special register or a character or graphic string expression that specifies the
user profile name to use as the job user filtering criteria.
The string can be a user name or one of the following special values:

*ALL All jobs being processed under all user names.


*USER The user part of the qualified job name.

The USER special register is specified as a non-string value. It represents the current
user of the job invoking the function.
If this parameter is not provided, the value of the USER special register is used.
job- A character or graphic string expression that specifies the type of submitted jobs to
submitter- return. The string must be one of the following values:
filter
*ALL All submitted jobs.
*JOB Jobs that were submitted from the same job that is invoking this function.
*USER Jobs that were submitted from a job having the same user profile as the job
invoking this function.
*WRKSTN Jobs that were submitted from the same work station as the job invoking
this function.

If this parameter is not provided, a value of *ALL is used.

Restrictions:
• Only one of these filters can have a value other than *ALL: job-subsystem-filter and job-submitter-filter.
• If a value other than *ALL is specified for job-submitter-filter, you must specify *ALL for job-user-filter.
Notes:
• Jobs submitted with *NO specified for the Allow display by WRKSBMJOB (DSPSBMJOB) parameter of
the SBMJOB command are not returned by this table function.
For each of the WRKSBMJOB, WRKSBSJOB, and WRKUSRJOB CL commands shown below, the
corresponding invocation of JOB_INFO will return the same list of jobs. Note that to get exact
equivalence, predicates must be added to some queries to achieve equivalent results:
• For equivalence with WRKUSRJOB, a query must always include the predicate WHERE JOB_TYPE NOT
IN ('SBS','SYS','RDR','WTR')
• For equivalence with WRKSBSJOB SBS(*OUTQ) or WRKSBSJOB SBS(*ALL), a query must always include
the predicate WHERE JOB_TYPE NOT IN ('SBS','SYS')

Database performance and query optimization 1047


Table 268. Equivalent CL command and JOB_INFO invocations
CL Command CL Parameters JOB_INFO invocation
WRKSBMJOB SBMFROM(*USER) SELECT * FROM TABLE(QSYS2.JOB_INFO(
JOB_SUBMITTER_FILTER => '*USER',
JOB_USER_FILTER => '*ALL'
)) X

SBMFROM(*WRKST SELECT * FROM TABLE(QSYS2.JOB_INFO(


N) JOB_SUBMITTER_FILTER => '*WRKSTN',
JOB_USER_FILTER => '*ALL'
)) X

SBMFROM(*JOB) SELECT * FROM TABLE(QSYS2.JOB_INFO(


JOB_SUBMITTER_FILTER => '*JOB',
JOB_USER_FILTER => '*ALL'
)) X

WRKSBSJOB SBS(QBATCH) SELECT * FROM TABLE(QSYS2.JOB_INFO(


USER(*ALL) JOB_SUBSYSTEM_FILTER => 'QBATCH',
JOB_USER_FILTER => '*ALL'
)) X

SBS(*JOBQ) SELECT * FROM TABLE(QSYS2.JOB_INFO(


USER(*ALL) JOB_STATUS_FILTER => '*JOBQ',
JOB_USER_FILTER => '*ALL'
)) X

SBS(*OUTQ) SELECT * FROM TABLE(QSYS2.JOB_INFO(


USER(JOEUSER) JOB_STATUS_FILTER => '*OUTQ',
JOB_USER_FILTER => 'JOEUSER'
)) X
WHERE JOB_TYPE NOT IN ('SBS','SYS')

SBS(*ALL) SELECT * FROM TABLE(QSYS2.JOB_INFO(


USER(*ALL) JOB_STATUS_FILTER => '*ALL',
JOB_USER_FILTER => '*ALL'
)) X
WHERE JOB_TYPE NOT IN ('SBS','SYS')

1048 IBM i: Performance and Query Optimization


Table 268. Equivalent CL command and JOB_INFO invocations (continued)
CL Command CL Parameters JOB_INFO invocation
WRKUSRJOB USER(*) SELECT * FROM TABLE(QSYS2.JOB_INFO(
STATUS(*ALL) )) X
WHERE JOB_TYPE NOT IN ('SBS','SYS','RDR','WTR')
JOBTYPE(*ALL)

USER(*) SELECT * FROM TABLE(QSYS2.JOB_INFO(


STATUS(*ALL) JOB_TYPE_FILTER => '*INTERACT'
)) X
JOBTYPE(*INTERAC WHERE JOB_TYPE NOT IN ('SBS','SYS','RDR','WTR')
T)

USER(JOEUSER) SELECT * FROM TABLE(QSYS2.JOB_INFO(


STATUS(*ACTIVE) JOB_USER_FILTER => 'JOEUSER',
JOB_STATUS_FILTER => '*ACTIVE'
JOBTYPE(*ALL) )) X
WHERE JOB_TYPE NOT IN ('SBS','SYS','RDR','WTR')

USER(*) SELECT * FROM TABLE(QSYS2.JOB_INFO(


STATUS(*OUTQ) JOB_STATUS_FILTER => '*OUTQ'
)) X
JOBTYPE(*ALL) WHERE JOB_TYPE NOT IN ('SBS','SYS','RDR','WTR')

USER(*ALL) SELECT * FROM TABLE(QSYS2.JOB_INFO(


STATUS(*JOBQ) JOB_USER_FILTER => '*ALL',
JOB_STATUS_FILTER => *JOBQ',
JOBTYPE(*BATCH) JOB_TYPE_FILTER =>'*BATCH'
)) X
WHERE JOB_TYPE NOT IN ('SBS','SYS','RDR','WTR')

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 269. JOB_INFO table function

Column Name Data Type Description

JOB_NAME VARCHAR(28) The qualified job name.

JOB_NAME_SHORT VARCHAR(10) The name of the job.

JOB_USER VARCHAR(10) The user profile that started the job.

JOB_NUMBER VARCHAR(6) The job number of the job.

JOB_INFORMATION VARCHAR(12) Indicates whether information is available for the job.

NO The information is not available because the job was not


accessible.

YES The information is available.

When this value is NO, all columns other than JOB_NAME return the
null value.

Database performance and query optimization 1049


Table 269. JOB_INFO table function (continued)

Column Name Data Type Description

JOB_STATUS VARCHAR(6) The status of the job.

ACTIVE The job has started, and it can use system resources
(processing unit, main storage, and so on). This does not
guarantee that the job is currently running, however. For
example, an active job may be in one of the following
states where it is not in a position to use system
resources:
• The Hold Job (HLDJOB) command holds the job; the
Release Job (RLSJOB) command allows the job to run
again.
• The Transfer Group Job (TFRGRPJOB) or Transfer
Secondary Job (TFRSECJOB) command suspends the
job. When control returns to the job, the job can run
again.
• The job is disconnected using the Disconnect Job
(DSCJOB) command. When the interactive user signs
back on, thereby connecting back into the job, the job
can run again.
• The job is waiting for any reason. For example, when
the job receives the reply for an inquiry message, the
job can start running again.

JOBQ The job is currently on a job queue. The job possibly was
previously active and was placed back on the job queue
because of the Transfer Job (TFRJOB) or Transfer Batch
Job (TFRBCHJOB) command, or the job was never active
because it was just submitted.

OUTQ The job has completed running and has spooled output
that has not yet printed or the job's job log has not yet
been written.

JOB_TYPE VARCHAR(3) The type of job.

ASJ Autostart

BCH Batch

BCI Batch Immediate

EVK Started by a procedure start request

INT Interactive

M36 Advanced 36 server job

MRT Multiple requester terminal

PDJ Print driver job

PJ Prestart job

RDR Spool reader

SBS Subsystem monitor

SYS System

WTR Spool writer

1050 IBM i: Performance and Query Optimization


Table 269. JOB_INFO table function (continued)

Column Name Data Type Description

JOB_TYPE_ENHANCED VARCHAR(28) The combined job type and job subtype values.

ALTERNATE_SPOOL_USER Batch - alternate spool


user

AUTOSTART Autostart job

BATCH Batch job

BATCH_IMMEDIATE Batch immediate job

BATCH_MRT Batch - System/36


multiple requester
terminal (MRT) job

COMM_PROCEDURE_START_REQUEST Communications job -


procedure start request
job

INTERACTIVE Interactive job

INTERACTIVE_GROUP Interactive job - Part of


group

INTERACTIVE_SYSREQ Interactive job - Part of


system request pair

INTERACTIVE_SYSREQ_AND_GROUP Interactive job - Part of


system request pair and
part of a group

PRESTART Prestart job

PRESTART_BATCH Prestart batch job

PRESTART_COMM Prestart communications


job

READER Reader job

SUBSYSTEM Subsystem job

SYSTEM System job (all system


jobs including SCPF)

WRITER Writer job (including both


spool writers and print
drivers)

JOB_SUBSYSTEM VARCHAR(10) The name of the subsystem for the job.


Contains the null value if JOB_TYPE is SYS, JOB_STATUS is JOBQ or
OUTQ, or if the job has no subsystem.

JOB_DATE VARCHAR(10) The date that is assigned to the job, in *ISO format. The job date
remains the same for the duration of the job unless it is changed by
the user. Can also contain the following special value:

SYSVAL This job will use the system date.

Contains the null value if JOB_STATUS is OUTQ.

JOB_DESCRIPTION_LIBRARY VARCHAR(10) The name of the library containing the job description.
Contains the null value if JOB_DESCRIPTION is null.

JOB_DESCRIPTION VARCHAR(10) The name of the job description used for this job.
Contains the null value if the job has no job description.

JOB_ACCOUNTING_CODE VARCHAR(15) An identifier assigned to the job by the system to collect resource use
information for the job when job accounting is active.
Contains the null value if the job has no accounting code.

SUBMITTER_JOB_NAME VARCHAR(28) The qualified job name of the submitter's job.


Contains the null value if the job has no submitter.

SUBMITTER_MESSAGE_QUEUE_LIBRARY VARCHAR(10) The name of the library containing the message queue.
Contains the null value if the job has no submitter.

Database performance and query optimization 1051


Table 269. JOB_INFO table function (continued)

Column Name Data Type Description

SUBMITTER_MESSAGE_QUEUE VARCHAR(10) The name of the message queue where the system sends a
completion message when a batch job ends.
Contains the null value if the job has no submitter.

SERVER_TYPE VARCHAR(30) The type of server represented by the job. See Server table for a list of
server type values.
Contains the null value if the job is not part of a server.

JOB_ENTERED_SYSTEM_TIME TIMESTAMP(0) The timestamp for when the job was placed on the system.

JOB_SCHEDULED_TIME TIMESTAMP(0) The timestamp for when the job is scheduled to become active.
Contains the null value if this is not a scheduled job.

JOB_ACTIVE_TIME TIMESTAMP(0) The time the job began to run on the system.
Contains the null value if the job did not become active.

JOB_END_TIME TIMESTAMP(0) The timestamp for when the job completed running on the system.
Contains the null value if the job has not ended.

JOB_END_SEVERITY SMALLINT The message severity level of escape messages that can cause a
batch job to end. The batch job ends when a request in the batch
input stream sends an escape message, whose severity is equal to or
greater than this value, to the request processing program.

COMPLETION_STATUS VARCHAR(8) The completion status of the job.

ABNORMAL The job completed abnormally.

NORMAL The job completed normally.

Contains the null value if this the job has not completed.

JOB_END_REASON VARCHAR(60) The most recent action that caused the job to end. Contains one of the
following values:
• JOB ENDED DUE TO A DEVICE ERROR
• JOB ENDED DUE TO A SIGNAL
• JOB ENDED DUE TO AN UNHANDLED ERROR
• JOB ENDED DUE TO THE CPU LIMIT BEING EXCEEDED
• JOB ENDED DUE TO THE DISCONNECT TIME INTERVAL BEING
EXCEEDED
• JOB ENDED DUE TO THE INACTIVITY TIME INTERVAL BEING
EXCEEDED
• JOB ENDED DUE TO THE MESSAGE SEVERITY LEVEL BEING
EXCEEDED
• JOB ENDED DUE TO THE STORAGE LIMIT BEING EXCEEDED
• JOB ENDED WHILE IT WAS STILL ON A JOB QUEUE
• JOB ENDING ABNORMALLY
• JOB ENDING IMMEDIATELY
• JOB ENDING IN NORMAL MANNER
• JOB ENDING NORMALLY AFTER A CONTROLLED END WAS
REQUESTED
• SYSTEM ENDED ABNORMALLY
Contains the null value if job is not currently ending.

JOB_QUEUE_LIBRARY VARCHAR(10) The name of the library containing the job queue.
Contains the null value if JOB_STATUS is OUTQ or if job is not on a job
queue and the job is not a batch job that was started from a job queue.

JOB_QUEUE_NAME VARCHAR(10) The name of the job queue that the job is currently on, or that the job
was on if it is currently active.
Contains the null value if JOB_STATUS is OUTQ or if job is not on a job
queue and the job is not a batch job that was started from a job queue.

1052 IBM i: Performance and Query Optimization


Table 269. JOB_INFO table function (continued)

Column Name Data Type Description

JOB_QUEUE_STATUS VARCHAR(9) The status of this job on the job queue.

HELD This job is being held on the job queue.

RELEASED This job is ready to be selected.

SCHEDULED This job will run as scheduled.

Contains the null value if the job is not on a job queue.

JOB_QUEUE_PRIORITY SMALLINT The scheduling priority of the job compared to other jobs on the same
job queue. The highest priority is 0 and the lowest is 9.
Contains the null value if JOB_STATUS is not JOBQ.

JOB_QUEUE_TIME TIMESTAMP(0) The timestamp when the job was put on the job queue.
Contains the null value if this the job is not on a job queue.

JOB_MESSAGE_QUEUE_MAXIMUM_SIZE SMALLINT The maximum size, in megabytes, that the job message queue can
become. The range is 2 to 64.
Contains the null value if JOB_QUEUE_NAME is null.

JOB_MESSAGE_QUEUE_FULL_ACTION VARCHAR(8) The action to take when the message queue is full.

*NOWRAP When the job message queue is full, do not wrap. This
action causes the job to end.

*PRTWRAP When the job message queue is full, wrap the


message queue and print the messages that are being
overlaid because of the wrapping.

*WRAP When the job message queue is full, wrap to the


beginning and start filling again.

Contains the null value if JOB_QUEUE_NAME is null.

ALLOW_MULTIPLE_THREADS VARCHAR(3) Indicates whether this job allows multiple user threads. This attribute
does not prevent the operating system from creating system threads
in the job.

NO This job does not allow multiple user threads.

YES This job allows multiple user threads.

PEAK_TEMPORARY_STORAGE INTEGER The maximum amount of auxiliary storage, in megabytes, that the job
has used.
Contains the null value if JOB_STATUS is OUTQ or for a job on a job
queue if a value has not been set for the job.

DEFAULT_WAIT INTEGER The default maximum time, in seconds, that a thread in the job
waits for a system instruction, such as a LOCK machine interface (MI)
instruction, to acquire a resource.
Contains the null value if there is no maximum, if JOB_STATUS is
OUTQ, or for a job on a job queue if a value has not been set for the
job.

MAXIMUM_PROCESSING_TIME_ INTEGER The maximum processing unit time, in milliseconds, that the job can
ALLOWED use. If the job consists of multiple routing steps, this is the maximum
processing unit time that the current routing step can use. If the
maximum time is exceeded, the job is held.
Contains the null value if JOB_STATUS is OUTQ or if no maximum
amount of processing unit time has been defined.

MAXIMUM_TEMPORARY_STORAGE_ INTEGER The maximum amount of auxiliary storage, in megabytes, that the
ALLOWED job can use. If the job consists of multiple routing steps, this is
the maximum temporary storage that the routing step can use. This
temporary storage is used for storage required by the program itself
and by implicitly created internal system objects used to support the
routing step. (It does not include storage for objects in the QTEMP
library.) If the maximum temporary storage is exceeded, the job is
held. This does not apply to the use of permanent storage, which is
controlled through the user profile.
Contains the null value if JOB_STATUS is OUTQ or if no maximum
amount of temporary storage has been defined.

Database performance and query optimization 1053


Table 269. JOB_INFO table function (continued)

Column Name Data Type Description

TIME_SLICE INTEGER The maximum amount of processor time, in milliseconds, given to


each thread in this job before other threads in this job and in other
jobs are given the opportunity to run. The time slice establishes
the amount of time needed by a thread in this job to accomplish
a meaningful amount of processing. At the end of the time slice,
the thread might be put in an inactive state so that other threads
can become active in the storage pool. Values range from 8 through
9999999.
Contains the null value if JOB_STATUS is OUTQ or for a job on a job
queue if a value has not been set for the job.

JOB_SWITCHES CHAR(8) The current setting of the job switches used by this job.
Contains the null value no job switches are set.

ROUTING_DATA VARCHAR(80) The routing data that is used to determine the routing entry that
identifies the program to start for the routing step.
Contains the null value if there is no routing data for this job.

CCSID INTEGER The coded character set identifier (CCSID) used for this job.
Contains the null value if no CCSID is defined for this job.

CHARACTER_IDENTIFIER_CONTROL VARCHAR(9) The character identifier control for the job. This attribute controls the
type of CCSID conversion that occurs for display files, printer files,
and panel groups. The *CHRIDCTL special value must be specified on
the CHRID command parameter on the create, change, or override
command for display files, printer files, and panel groups before this
attribute will be used.

*DEVD The *DEVD special value performs the same function


as on the CHRID command parameter for display files,
printer files, and panel groups.

*JOBCCSID The *JOBCCSID special value performs the same


function as on the CHRID command parameter for
display files, printer files, and panel groups.

SORT_SEQUENCE_LIBRARY VARCHAR(10) The name or the library that contains the sort sequence table.
Contains the null value if no sort sequence table is defined for this job
or if SORT_SEQUENCE_NAME is a special value.

SORT_SEQUENCE_NAME VARCHAR(10) The name of the sort sequence table associated with this job.
Contains the null value if no sort sequence table is defined for this job.

LANGUAGE_ID CHAR(3) The language identifier associated with this job.

COUNTRY_ID CHAR(2) The country or region identifier associated with this job.

DATE_FORMAT CHAR(4) The date format used for this job.

*DMY Day, month, year format.

*JUL Julian format (year and day).

*MDY Month, day, year format.

*YMD Year, month, day format.

DATE_SEPARATOR CHAR(1) The date separator used for this job.

TIME_SEPARATOR CHAR(1) The time separator used for this job.

1054 IBM i: Performance and Query Optimization


Table 269. JOB_INFO table function (continued)

Column Name Data Type Description

DECIMAL_FORMAT VARCHAR(6) The decimal format used for this job.

*BLANK Uses a period for a decimal point, a comma for a 3-digit


grouping character, and zero-suppress to the left of the
decimal point.

J Uses a comma for a decimal point and a period for a 3-


digit grouping character. The zero-suppression character
is in the second position (rather than the first) to the
left of the decimal notation. Balances with zero values
to the left of the comma are written with one leading
zero (0,04). The J entry also overrides any edit codes that
might suppress the leading zero.

I Uses a comma for a decimal point, a period for a 3-digit


grouping character, and zero-suppress to the left of the
decimal point.

TIME_ZONE_DESCRIPTION_NAME VARCHAR(10) The name of the time zone description that is used to calculate local
job time.

MESSAGE_LOGGING_LEVEL SMALLINT The type of information that is logged.

0 No messages are logged.

1 All messages sent to the job's external message queue with a


severity greater than or equal to the message logging severity are
logged. This includes the indication of job start, job end and job
completion status.

2 The following information is logged:


• Level 1 information
• Request messages that result in a high-level message with
a severity code greater than or equal to the logging severity
cause the request message and all associated messages to be
logged.
Note: A high-level message is one that is sent to the program
message queue of the program that receives the request
message. For example, QCMD is an IBM-supplied request
processing program that receives request messages.

3 The following information is logged:


• Level 1 and 2 information
• All request messages
• Commands run by a CL program are logged if it is allowed by
the logging of CL programs job attribute and the log attribute
of the CL program.

4 The following information is logged:


• All request messages and all messages with a severity greater
than or equal to the message logging severity, including trace
messages.
• Commands run by a CL program are logged if it is allowed by
the logging of CL programs job attribute and the log attribute
of the CL program.

MESSAGE_LOGGING_SEVERITY SMALLINT The severity level that is used in conjunction with the logging level to
determine which error messages are logged in the job log. The values
range from 0 through 99.

MESSAGE_LOGGING_TEXT VARCHAR(7) The level of message text that is written in the job log when a message
is logged according to the logging level and logging severity.

*MSG Only the message text is written to the job log.

*NOLIST If the job ends normally, no job log is produced. If the job
ends abnormally (the job end code is 20 or higher), a job
log is produced. The messages that appear in the job log
contain both the message text and the message help.

*SECLVL Both the message text and the message help (cause and
recovery) of the error message are written to the job log.

Database performance and query optimization 1055


Table 269. JOB_INFO table function (continued)

Column Name Data Type Description

LOG_CL_PROGRAM_COMMANDS VARCHAR(4) Specifies whether or not commands are logged for CL programs that
are run.

*NO Commands are not logged.

*YES Commands are logged.

STATUS_MESSAGE VARCHAR(7) Specifies whether status messages are displayed for this job.

*NONE This job does not display status messages.

*NORMAL This job displays status messages.

INQUIRY_MESSAGE_REPLY VARCHAR(8) Specifies how the job answers inquiry messages.

*RQD The job requires an answer for any inquiry messages


that occur while this job is running.

*DFT The system uses the default message reply to answer


any inquiry messages issued while this job is running.
The default reply is either defined in the message
description or is the default system reply.

*SYSRPYL The system reply list is checked to see if there is an


entry for an inquiry message issued while this job is
running. If a match occurs, the system uses the reply
value for that entry. If no entry exists for that message,
the system uses an inquiry message.

BREAK_MESSAGE VARCHAR(7) Specifies how this job handles break messages.

*HOLD The message queue holds break messages until a user


or program requests them. The work station user uses
the Display Message (DSPMSG) command to display the
messages; a program must issue a Receive Message
(RCVMSG) command to receive a message and handle
it.

*NORMAL The message queue status determines break message


handling.

*NOTIFY The system notifies the job's message queue when a


message arrives. For interactive jobs, the audible alarm
sounds if there is one, and the message-waiting light
comes on.

JOB_LOG_OUTPUT VARCHAR(10) Specifies how the job log will be produced when the job completes.

*JOBEND The job log will be produced by the job itself. If the
job cannot produce its own job log, the job log will
be produced by a job log server. For example, a job
does not produce its own job log when the system
is processing a Power Down System (PWRDWNSYS)
command.

*JOBLOGSVR The job log will be produced by a job log server. For
more information about job log servers, refer to the
Start Job Log Server (STRLOGSVR) command.

*PND The job log will not be produced. The job log
remains pending until removed.

JOB_LOG_PENDING VARCHAR(3) Specifies whether there is a job log that has not yet been written. The
writing of the job log may become pending based on the value of the
job log output job attribute when the job completes its activity.

NO Job log is not pending.

YES Job log is pending.

OUTPUT_QUEUE_PRIORITY SMALLINT The output priority for spooled output files that this job produces. The
highest priority is 0, and the lowest is 9.

OUTPUT_QUEUE_LIBRARY VARCHAR(10) The name of the library that contains the default output queue.

OUTPUT_QUEUE_NAME VARCHAR(10) The name of the default output queue that is used for spooled output
produced by this job and the name of the library that contains the
output queue. The default output queue is only for spooled printer
files that specify *JOB for the output queue.

1056 IBM i: Performance and Query Optimization


Table 269. JOB_INFO table function (continued)

Column Name Data Type Description

SPOOLED_FILE_ACTION VARCHAR(7) Specifies whether spooled files are accessed through job interfaces
after the job has completed is normal activity.

*DETACH The spooled files are detached from the job when the
job completes its activity.

*KEEP When the job completes its activity, as long as at least


one spooled file for the job exists in the system auxiliary
storage pool (ASP 1) or in a basic user ASP (ASPs
2-32), the spooled files are kept with the job and the
status of the job is updated to indicate that the job
has completed. If all remaining spooled files for the job
are in independent ASPs (ASPs 33-255), the spooled
files will be detached from the job and the job will be
removed from the system.

PRINTER_DEVICE_NAME VARCHAR(10) The printer device used for printing output from this job.

PRINT_KEY_FORMAT VARCHAR(7) Specifies whether border and header information is provided when the
Print key is pressed.

*NONE The border and header information is not included with


output from the Print key.

*PRTBDR The border information is included with output from the


Print key.

*PRTHDR The header information is included with output from the


Print key.

*PRTALL The border and header information is included with


output from the Print key.

PRINT_TEXT VARCHAR(30) The line of text that is printed at the bottom of each page of printed
output for the job.
Contains the null value if there is no text defined to print at the bottom
of each page.

DEVICE_NAME VARCHAR(10) The name of the device as identified to the system. For an interactive
job it is the device where the job started.
Contains the null value if this is not an interactive job.

DEVICE_RECOVERY_ACTION VARCHAR(13) The action taken for interactive jobs when an I/O error occurs for the
job's requesting program device.

*DSCENDRQS Disconnects the job when an I/O error occurs.


When the job reconnects, the system sends
the End Request (ENDRQS) command to return
control to the previous request level.

*DSCMSG Disconnects the job when an I/O error occurs.


When the job reconnects, the system sends
an error message to the application program,
indicating the job has reconnected and that the
work station device has recovered.

*ENDJOB Ends the job when an I/O error occurs. A


message is sent to the job's log and to the
history log (QHST) indicating the job ended
because of a device error.

*ENDJOBNOLIST Ends the job when an I/O error occurs. There


is no job log produced for the job. The system
sends a message to the QHST log indicating the
job ended because of a device error.

*MSG Signals the I/O error message to the application


and lets the application program perform error
recovery.

Contains the null value if this is not an interactive job.

Database performance and query optimization 1057


Table 269. JOB_INFO table function (continued)

Column Name Data Type Description

DDM_CONVERSATION VARCHAR(5) Specifies whether connections using distributed data management


(DDM) protocols remain active when they are not being used. The
connections include APPC conversations, active TCP/IP connections or
Opti-Connect connections.

*DROP The system ends a DDM connection when there are no


users. Examples include when an application closes a DDM
file, or when a DRDA application runs a SQL DISCONNECT
statement.

*KEEP The system keeps DDM connections active when there are
no users, except for the following:
• The routing step ends on the source system. The routing
step ends when the job ends or when the job is rerouted
to another routing step.
• The Reclaim Distributed Data Management Conversation
(RCLDDMCNV) command or the Reclaim Resources
(RCLRSC) command runs.
• A communications failure or an internal failure occurs.
• A DRDA connection to an application server not running
on the system ends.

MODE_NAME VARCHAR(8) The mode name of the advanced program-to-program


communications device that started the job. The following special
value may be returned:

*BLANK The mode name is a blank name.

Contains the null value if the job is not using advanced program-to-
program communications (APPC).

UNIT_OF_WORK_ID CHAR(24) The unit of work ID is used to track jobs across multiple systems.
Contains the null value if the job is not associated with a source or
target system using advanced program-to-program communications
(APPC).

INTERNAL_JOB_ID BINARY(16) The internal job identifier.

Examples
• Find all interactive jobs.

SELECT * FROM TABLE(QSYS2.JOB_INFO(JOB_TYPE_FILTER => '*INTERACT')) X;

• Find jobs submitted by SCOTTF that have not been started.

SELECT * FROM TABLE(QSYS2.JOB_INFO(JOB_USER_FILTER => 'SCOTTF',


JOB_STATUS_FILTER => '*JOBQ')) X;

JOB_LOCK_INFO table function


The JOB_LOCK_INFO table function returns a list of objects that have been locked or have lower level
locks acquired by the specified job. If the job is not active, no rows are returned.
This information is similar to what is returned by the Retrieve Job Locks (QWCRJBLK) API.
Authorization: None required to see information for jobs where the caller's user profile is the same as the
job user identity of the job for which the information is being returned. Otherwise, the caller must have
*JOBCTL special authority.

1058 IBM i: Performance and Query Optimization


JOB_LOCK_INFO ( job-name
JOB_NAME =>

, internal-objects
INTERNAL_OBJECTS =>

)
, ignore-errors
IGNORE_ERRORS =>

The schema is QSYS2.

job-name A character or graphic string expression that identifies the qualified name of a job. The
special value of '*' indicates the current job.
internal- A character or graphic string expression that indicates whether rows are returned for
objects internal objects.

NO Only external objects are returned. This is the default.


YES Rows for internal objects and internal space objects are returned in addition to
external objects.

ignore-errors A character or graphic string expression that identifies what to do when an error is
encountered.

NO An error is returned.

YES A warning is returned.


No row is returned when an error is encountered. This is the default.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 270. JOB_LOCK_INFO table function

Column Name Data Type Description

LOCK_CATEGORY VARCHAR(23) The type of entity to which this row of lock information applies.

EXTERNAL IBM i external object

EXTERNAL SPACE IBM i external object space location


LOCATION

INTERNAL Internal system object


This type of row is only returned if the internal-
objects parameter value is YES.

INTERNAL SPACE Internal system object space location


LOCATION This type of row is only returned if the internal-
objects parameter value is YES.

LOCK SPACE Lock space object

MEMBER Member object

Contains the null value if LOCK_CATEGORY is not known.

OBJECT_LIBRARY VARCHAR(10) The name of the library containing the locked object.
Contains the null value if LOCK_CATEGORY is INTERNAL or INTERNAL
SPACE LOCATION or if the library name cannot be determined.

Database performance and query optimization 1059


Table 270. JOB_LOCK_INFO table function (continued)

Column Name Data Type Description

OBJECT_NAME VARCHAR(30) The name of the object that is locked.


If LOCK_CATEGORY is MEMBER, the object name is the name of the file
that owns the member. If the MEMBER_LOCK_TYPE is MEMBER or ACCESS
PATH, the file that owns the member may be either a physical file or a
logical file. If the MEMBER_LOCK_TYPE is DATA, the file that owns the
member will be a physical file.
If LOCK_CATEGORY is LOCK SPACE, the name is the lock space id for that
lock space.
Contains the null value if is LOCK_CATEGORY is INTERNAL or INTERNAL
SPACE LOCATION and the user does not have *JOBCTL special authority or
if the object name cannot be determined.

OBJECT_TYPE VARCHAR(7) The object type. If the lock is on a database member the object type will be
*FILE.

OBJECT_ATTRIBUTE VARCHAR(10) The extended attribute value for this object's type.
Contains the null value if there is no extended attribute associated with the
object type.

LOCK_STATE VARCHAR(7) The lock condition for the lock request. Lower level locks are returned and
can occur when a member of a file is locked but the file itself is not locked.

*EXCL Lock exclusive, no read allowed.

*EXCLRD Lock exclusive, read allowed.

*SHRNUP Lock shared, no update.

*SHRRD Lock shared for read.

*SHRUPD Lock shared for update.

Contains the null value if the object is not locked but there are locks on
lower level objects.

LOCK_STATUS VARCHAR(17) The status of the lock request.

ASYNCHRONOUS The job or thread has a lock request outstanding


WAIT for this object (asynchronous). The lock may be a
single request or part of a multiple lock request for
which some other object specified in the request
has been identified as unavailable.

HELD The lock on this object currently is held by the job


or thread.

SYNCHRONOUS The job or thread is waiting to get the lock on this


WAIT object (synchronous).

Contains the null value if the object is not locked but there are locks on
lower level objects.

LOCK_COUNT INTEGER The number of identical locks on this entity.

LOCK_SCOPE VARCHAR(10) The scope of the lock. Lower level locks are returned and can occur when a
member of a file is locked but the file itself is not locked.

JOB The lock is scoped to the job.

LOCK SPACE The lock is scoped to a lock space.

THREAD The lock is scoped to a thread.

Contains the null value if the object is not locked but there are locks on
lower level objects.

MEMBER_LOCKS INTEGER The number of member locks for a database file.


Contains the null value if the object is not a database file.

MEMBER_NAME VARCHAR(10) The name of the member that has a lock held or waiting on it. Contains *N if
the member name cannot be determined.
Contains the null value if LOCK_CATEGORY is not MEMBER.

1060 IBM i: Performance and Query Optimization


Table 270. JOB_LOCK_INFO table function (continued)

Column Name Data Type Description

MEMBER_LOCK_TYPE VARCHAR(11) The type of member lock.

ACCESS PATH The lock is an access path lock.

DATA The lock is a data lock.

MEMBER The lock is a member lock.

Contains the null value if LOCK_CATEGORY is not MEMBER.

SPACE_LOCATION_LOCK_OFFSET BIGINT A value in bytes to the location in the space that is locked.
Contains the null value if LOCK_CATEGORY is not EXTERNAL SPACE
LOCATION or INTERNAL SPACE LOCATION.

LOCK_SPACE_ID BINARY(20) The identifier of the lock space for which the lock is being waited on.
Contains the null value if LOCK_SCOPE is not LOCK SPACE.

THREAD_ID BIGINT A value which uniquely identifies a thread within a job holding a thread
scope lock or the thread waiting for a lock.
Contain the null value if this lock is not thread scoped.

THREAD_HANDLE INTEGER A value which addresses a particular thread within a job holding a thread
scope lock or the thread waiting for a lock.
Contain the null value if this lock is not thread scoped.

ASP_NAME VARCHAR(10) The name of the Auxiliary Storage Pool (ASP) that contains the object that is
locked.
Contains the null value if the name of the ASP device cannot be determined.

ASP_NUMBER INTEGER The numeric identifier of the ASP containing the locked object.
Contains the null value if the name of the ASP device cannot be determined.

OBJECT_LOCK_HANDLE BINARY(64) An identifier that can be input to Retrieve Lock Information (QWCRLCKI) API
to find additional information about other holders of locks on this object.
Contains the null value if additional information cannot be retrieved.

LOCK_REQUEST_HANDLE BINARY(64) A handle to lock request information. Using the Retrieve Lock Request
Information (QWCRLRQI) API and passing in this handle you can retrieve
additional information about the program that requested this lock.
Contains the null value if additional information cannot be retrieved.

Example
• Retrieve information about locks for the current job.

SELECT * FROM TABLE(QSYS2.JOB_LOCK_INFO('*'));

JOB_QUEUE_ENTRIES view
The JOB_QUEUE_ENTRIES view returns one row for each entry in a job queue.
Authorization: See Note below.
The following table describes the columns in the view. The system name is JOBQ_ENT. The schema is
SYSTOOLS.
Table 271. JOB_QUEUE_ENTRIES view

Column Name System Column Name Data type Description

JOB_QUEUE_LIBRARY JOBQ_LIB VARCHAR(10) The name of the library containing the job queue.

JOB_QUEUE_NAME JOBQ VARCHAR(10) The name of the job queue that the job is currently
on.

Database performance and query optimization 1061


Table 271. JOB_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data type Description

JOB_QUEUE_STATUS STATUS VARCHAR(9) The status of this job on the job queue.

HELD This job is being held on the job


queue.

RELEASED This job is ready to be selected.

SCHEDULED This job will run as scheduled.

JOB_NAME JOB_NAME VARCHAR(28) The qualified job name.

JOB_NAME_SHORT JOB_NAME_S VARCHAR(10) The name of the job.

JOB_USER JOB_USER VARCHAR(10) The user profile that started the job.

JOB_NUMBER JOB_NUMBER VARCHAR(6) The job number of the job.

JOB_TYPE JOB_TYPE VARCHAR(3) The type of job.

ASJ Autostart

BCH Batch

BCI Batch Immediate

EVK Started by a procedure start request

INT Interactive

M36 Advanced 36 server job

MRT Multiple requester terminal

PDJ Print driver job

PJ Prestart job

RDR Spool reader

SBS Subsystem monitor

SYS System

WTR Spool writer

1062 IBM i: Performance and Query Optimization


Table 271. JOB_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data type Description

JOB_TYPE_ENHANCED JOBT_ENH VARCHAR(28) The combined job type and job subtype values.

ALTERNATE_SPOOL_USER Batch - alternate


spool user

AUTOSTART Autostart job

BATCH Batch job

BATCH_IMMEDIATE Batch
immediate job

BATCH_MRT Batch -
System/36
multiple
requester
terminal (MRT)
job

COMM_PROCEDURE_START_REQUEST Communications
job - procedure
start request job

INTERACTIVE Interactive job

INTERACTIVE_GROUP Interactive job -


Part of group

INTERACTIVE_SYSREQ Interactive job -


Part of system
request pair

INTERACTIVE_SYSREQ_AND_GROUP Interactive job -


Part of system
request pair and
part of a group

PRESTART Prestart job

PRESTART_BATCH Prestart batch


job

PRESTART_COMM Prestart
communications
job

READER Reader job

SUBSYSTEM Subsystem job

SYSTEM System job (all


system jobs
including SCPF)

WRITER Writer job


(including both
spool writers
and print
drivers)

JOB_DATE JOB_DATE VARCHAR(10) The date that is assigned to the job, in *ISO format.
The job date remains the same for the duration of
the job unless it is changed by the user. Can also
contain the following special value:

SYSVAL This job will use the system date.

JOB_DESCRIPTION_LIBRARY JOBDLIB VARCHAR(10) The name of the library containing the job
description.
Nullable
Contains the null value if JOB_DESCRIPTION is null.

JOB_DESCRIPTION JOBD VARCHAR(10) The name of the job description used for this job.

Nullable Contains the null value if the job has no job


description.

JOB_ACCOUNTING_CODE ACGCDE VARCHAR(15) An identifier assigned to the job by the system to


collect resource use information for the job when
Nullable job accounting is active.
Contains the null value if the job has no accounting
code.

Database performance and query optimization 1063


Table 271. JOB_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data type Description

SUBMITTER_JOB_NAME SBMJOBNAME VARCHAR(28) The qualified job name of the submitter's job.

Nullable Contains the null value if the job has no submitter.

SUBMITTER_MESSAGE_QUEUE_LIBRARY SBMMSGQLIB VARCHAR(10) The name of the library containing the message
queue.
Nullable
Contains the null value if the job has no submitter.

SUBMITTER_MESSAGE_QUEUE SBMMSGQ VARCHAR(10) The name of the message queue where the system
sends a completion message when a batch job ends.
Nullable
Contains the null value if the job has no submitter.

SERVER_TYPE SERVERTYPE VARCHAR(30) The type of server represented by the job. See
Server table for a list of server type values.
Nullable
Contains the null value if the job is not part of a
server.

JOB_ENTERED_SYSTEM_TIME ENTER_TIME TIMESTAMP(0) The timestamp for when the job was placed on the
system.

JOB_SCHEDULED_TIME JOB_SCHEDT TIMESTAMP(0) The timestamp for when the job is scheduled to
become active.
Nullable
Contains the null value if this is not a scheduled job.

JOB_END_SEVERITY JOB_ENDSEV INTEGER The message severity level of escape messages that
can cause a batch job to end. The batch job ends
when a request in the batch input stream sends
an escape message, whose severity is equal to or
greater than this value, to the request processing
program.

JOB_QUEUE_PRIORITY JOBQ_PRI INTEGER The scheduling priority of the job compared to other
jobs on the same job queue. The highest priority is 0
and the lowest is 9.

JOB_QUEUE_TIME JOBQ_TIME TIMESTAMP(0) The timestamp when the job was put on the job
queue.

JOB_MESSAGE_QUEUE_MAXIMUM_SIZE MSGQ_MAX INTEGER The maximum size, in megabytes, that the job
message queue can become. The range is 2 to 64.

JOB_MESSAGE_QUEUE_FULL_ACTION MSGQ_FULL VARCHAR(8) The action to take when the message queue is full.

*NOWRAP When the job message queue is full,


do not wrap. This action causes the
job to end.

*PRTWRAP When the job message queue is


full, wrap the message queue and
print the messages that are being
overlaid because of the wrapping.

*WRAP When the job message queue is


full, wrap to the beginning and start
filling again.

ALLOW_MULTIPLE_THREADS ALWMLTTHD VARCHAR(3) Indicates whether this job allows multiple user
threads. This attribute does not prevent the
operating system from creating system threads in
the job.

NO This job does not allow multiple user


threads.

YES This job allows multiple user threads.

DEFAULT_WAIT DFT_WAIT INTEGER The default maximum time, in seconds, that a


thread in the job waits for a system instruction,
Nullable such as a LOCK machine interface (MI) instruction,
to acquire a resource.
Contains the null value if there is no maximum or if a
value has not been set for the job.

1064 IBM i: Performance and Query Optimization


Table 271. JOB_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data type Description

MAXIMUM_PROCESSING_TIME_ MAX_TIME INTEGER The maximum processing unit time, in milliseconds,


ALLOWED that the job can use. If the job consists of multiple
Nullable routing steps, this is the maximum processing unit
time that the current routing step can use. If the
maximum time is exceeded, the job is held.
Contains the null value if no maximum amount of
processing unit time has been defined.

MAXIMUM_TEMPORARY_STORAGE_ MAX_STG INTEGER The maximum amount of auxiliary storage, in


ALLOWED megabytes, that the job can use. If the job consists
Nullable of multiple routing steps, this is the maximum
temporary storage that the routing step can use.
This temporary storage is used for storage required
by the program itself and by implicitly created
internal system objects used to support the routing
step. (It does not include storage for objects in the
QTEMP library.) If the maximum temporary storage
is exceeded, the job is held. This does not apply to
the use of permanent storage, which is controlled
through the user profile.
Contains the null value if no maximum amount of
temporary storage has been defined.

TIME_SLICE TIME_SLICE INTEGER The maximum amount of processor time, in


milliseconds, given to each thread in this job before
Nullable other threads in this job and in other jobs are given
the opportunity to run. The time slice establishes
the amount of time needed by a thread in this job
to accomplish a meaningful amount of processing.
At the end of the time slice, the thread might be
put in an inactive state so that other threads can
become active in the storage pool. Values range
from 8 through 9999999.
Contains the null value if a value has not been set for
the job.

JOB_SWITCHES SWITCHES CHAR(8) The current setting of the job switches used by this
job.
Nullable
Contains the null value no job switches are set.

ROUTING_DATA RTGDTA VARCHAR(80) The routing data that is used to determine the
routing entry that identifies the program to start for
Nullable the routing step.
Contains the null value if there is no routing data for
this job.

CCSID CCSID INTEGER The coded character set identifier (CCSID) used for
this job.
Nullable
Contains the null value if no CCSID is defined for this
job.

CHARACTER_IDENTIFIER_CONTROL CHRIDCTL VARCHAR(9) The character identifier control for the job. This
attribute controls the type of CCSID conversion
that occurs for display files, printer files, and panel
groups. The *CHRIDCTL special value must be
specified on the CHRID command parameter on the
create, change, or override command for display
files, printer files, and panel groups before this
attribute will be used.

*DEVD The *DEVD special value performs


the same function as on the CHRID
command parameter for display
files, printer files, and panel groups.

*JOBCCSID The *JOBCCSID special value


performs the same function as on
the CHRID command parameter for
display files, printer files, and panel
groups.

Database performance and query optimization 1065


Table 271. JOB_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data type Description

SORT_SEQUENCE_LIBRARY SRTSEQ_LIB VARCHAR(10) The name or the library that contains the sort
sequence table.
Nullable
Contains the null value if no sort sequence table is
defined for this job or if SORT_SEQUENCE_NAME is
a special value.

SORT_SEQUENCE_NAME SRTSEQ VARCHAR(10) The name of the sort sequence table associated
with this job.
Nullable
Contains the null value if no sort sequence table is
defined for this job.

LANGUAGE_ID LANGID CHAR(3) The language identifier associated with this job.

COUNTRY_ID COUNTRY_ID CHAR(2) The country or region identifier associated with this
job.

DATE_FORMAT DATFMT CHAR(4) The date format used for this job.

*DMY Day, month, year format.

*JUL Julian format (year and day).

*MDY Month, day, year format.

*YMD Year, month, day format.

DATE_SEPARATOR DATSEP CHAR(1) The date separator used for this job.

TIME_SEPARATOR TIMSEP CHAR(1) The time separator used for this job.

DECIMAL_FORMAT DECFMT VARCHAR(6) The decimal format used for this job.

*BLANK Uses a period for a decimal point, a


comma for a 3-digit grouping character,
and zero-suppress to the left of the
decimal point.

J Uses a comma for a decimal point and a


period for a 3-digit grouping character.
The zero-suppression character is in
the second position (rather than the
first) to the left of the decimal notation.
Balances with zero values to the left of
the comma are written with one leading
zero (0,04). The J entry also overrides
any edit codes that might suppress the
leading zero.

I Uses a comma for a decimal point, a


period for a 3-digit grouping character,
and zero-suppress to the left of the
decimal point.

TIME_ZONE_DESCRIPTION_NAME TIME_ZONE VARCHAR(10) The name of the time zone description that is used
to calculate local job time.

1066 IBM i: Performance and Query Optimization


Table 271. JOB_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data type Description

MESSAGE_LOGGING_LEVEL LOG_LEVEL INTEGER The type of information that is logged.

0 No messages are logged.

1 All messages sent to the job's external


message queue with a severity greater than
or equal to the message logging severity are
logged. This includes the indication of job start,
job end and job completion status.

2 The following information is logged:


• Level 1 information
• Request messages that result in a high-
level message with a severity code greater
than or equal to the logging severity cause
the request message and all associated
messages to be logged.
Note: A high-level message is one that is
sent to the program message queue of the
program that receives the request message.
For example, QCMD is an IBM-supplied
request processing program that receives
request messages.

3 The following information is logged:


• Level 1 and 2 information
• All request messages
• Commands run by a CL program are logged
if it is allowed by the logging of CL programs
job attribute and the log attribute of the CL
program.

4 The following information is logged:


• All request messages and all messages with
a severity greater than or equal to the
message logging severity, including trace
messages.
• Commands run by a CL program are logged
if it is allowed by the logging of CL programs
job attribute and the log attribute of the CL
program.

MESSAGE_LOGGING_SEVERITY LOG_SEV INTEGER The severity level that is used in conjunction with
the logging level to determine which error messages
are logged in the job log. The values range from 0
through 99.

MESSAGE_LOGGING_TEXT LOG_TEXT VARCHAR(7) The level of message text that is written in the
job log when a message is logged according to the
logging level and logging severity.

*MSG Only the message text is written to the


job log.

*NOLIST If the job ends normally, no job log is


produced. If the job ends abnormally
(the job end code is 20 or higher), a
job log is produced. The messages that
appear in the job log contain both the
message text and the message help.

*SECLVL Both the message text and the


message help (cause and recovery) of
the error message are written to the
job log.

LOG_CL_PROGRAM_COMMANDS LOG_CL VARCHAR(4) Specifies whether or not commands are logged for
CL programs that are run.

*NO Commands are not logged.

*YES Commands are logged.

Database performance and query optimization 1067


Table 271. JOB_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data type Description

STATUS_MESSAGE STATUS_MSG VARCHAR(7) Specifies whether status messages are displayed for
this job.

*NONE This job does not display status


messages.

*NORMAL This job displays status messages.

INQUIRY_MESSAGE_REPLY INQ_REPLY VARCHAR(8) Specifies how the job answers inquiry messages.

*RQD The job requires an answer for any


inquiry messages that occur while
this job is running.

*DFT The system uses the default message


reply to answer any inquiry messages
issued while this job is running. The
default reply is either defined in the
message description or is the default
system reply.

*SYSRPYL The system reply list is checked


to see if there is an entry for an
inquiry message issued while this
job is running. If a match occurs,
the system uses the reply value for
that entry. If no entry exists for that
message, the system uses an inquiry
message.

BREAK_MESSAGE BREAK_MSG VARCHAR(7) Specifies how this job handles break messages.

*HOLD The message queue holds break


messages until a user or program
requests them. The work station user
uses the Display Message (DSPMSG)
command to display the messages;
a program must issue a Receive
Message (RCVMSG) command to
receive a message and handle it.

*NORMAL The message queue status


determines break message handling.

*NOTIFY The system notifies the job's message


queue when a message arrives. For
interactive jobs, the audible alarm
sounds if there is one, and the
message-waiting light comes on.

JOB_LOG_OUTPUT JOBLOG_OUT VARCHAR(10) Specifies how the job log will be produced when the
job completes.

*JOBEND The job log will be produced by


the job itself. If the job cannot
produce its own job log, the
job log will be produced by a
job log server. For example, a
job does not produce its own
job log when the system is
processing a Power Down System
(PWRDWNSYS) command.

*JOBLOGSVR The job log will be produced


by a job log server. For more
information about job log servers,
refer to the Start Job Log Server
(STRLOGSVR) command.

*PND The job log will not be produced.


The job log remains pending until
removed.

OUTPUT_QUEUE_PRIORITY OUTQ_PRI INTEGER The output priority for spooled output files that
this job produces. The highest priority is 0, and the
lowest is 9.

OUTPUT_QUEUE_LIBRARY OUTQLIB VARCHAR(10) The name of the library that contains the default
output queue.

1068 IBM i: Performance and Query Optimization


Table 271. JOB_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data type Description

OUTPUT_QUEUE_NAME OUTQ VARCHAR(10) The name of the default output queue that is used
for spooled output produced by this job and the
name of the library that contains the output queue.
The default output queue is only for spooled printer
files that specify *JOB for the output queue.

SPOOLED_FILE_ACTION SPOOL_ACT VARCHAR(7) Specifies whether spooled files are accessed


through job interfaces after the job has completed
is normal activity.

*DETACH The spooled files are detached from


the job when the job completes its
activity.

*KEEP When the job completes its activity, as


long as at least one spooled file for
the job exists in the system auxiliary
storage pool (ASP 1) or in a basic
user ASP (ASPs 2-32), the spooled
files are kept with the job and the
status of the job is updated to indicate
that the job has completed. If all
remaining spooled files for the job are
in independent ASPs (ASPs 33-255),
the spooled files will be detached from
the job and the job will be removed
from the system.

PRINTER_DEVICE_NAME DEV_NAME VARCHAR(10) The printer device used for printing output from this
job.

PRINT_KEY_FORMAT PRINT_KEY VARCHAR(7) Specifies whether border and header information is


provided when the Print key is pressed.

*NONE The border and header information


is not included with output from the
Print key.

*PRTBDR The border information is included


with output from the Print key.

*PRTHDR The header information is included


with output from the Print key.

*PRTALL The border and header information is


included with output from the Print
key.

PRINT_TEXT PRINT_TEXT VARCHAR(30) The line of text that is printed at the bottom of each
page of printed output for the job.
Nullable
Contains the null value if there is no text defined to
print at the bottom of each page.

Database performance and query optimization 1069


Table 271. JOB_QUEUE_ENTRIES view (continued)

Column Name System Column Name Data type Description

DDM_CONVERSATION DDM_CONV VARCHAR(5) Specifies whether connections using distributed


data management (DDM) protocols remain active
when they are not being used. The connections
include APPC conversations, active TCP/IP
connections or Opti-Connect connections.

*DROP The system ends a DDM connection


when there are no users. Examples
include when an application closes a
DDM file, or when a DRDA application
runs a SQL DISCONNECT statement.

*KEEP The system keeps DDM connections


active when there are no users, except
for the following:
• The routing step ends on the source
system. The routing step ends when
the job ends or when the job is
rerouted to another routing step.
• The Reclaim Distributed
Data Management Conversation
(RCLDDMCNV) command or the
Reclaim Resources (RCLRSC)
command runs.
• A communications failure or an
internal failure occurs.
• A DRDA connection to an application
server not running on the system
ends.

MODE_NAME MODE_NAME VARCHAR(8) The mode name of the advanced program-to-


program communications device that started the
Nullable job. The following special value may be returned:

*BLANK The mode name is a blank name.

Contains the null value if the job is not using


advanced program-to-program communications
(APPC).

UNIT_OF_WORK_ID UWID CHAR(24) The unit of work ID is used to track jobs across
multiple systems.
Nullable
Contains the null value if the job is not associated
with a source or target system using advanced
program-to-program communications (APPC).

INTERNAL_JOB_ID JOB_ID BINARY(16) The internal job identifier.

Note
This function is provided in the SYSTOOLS schema as an example of how to create a view based on
information from a table function. Similar to other Db2 for i provided tools within SYSTOOLS, the SQL
source can be extracted and used as a model for building similar helper functions, or to create a
customized version within a user-specified schema.
Services provided in SYSTOOLS have authorization requirements that are determined by the interfaces
used to implement the service. To understand the authority requirements, extract the SQL for the service
and examine the implementation.

Example
List all the jobs on the APP1/BATCHJQ job queue.

SELECT * FROM SYSTOOLS.JOB_QUEUE_ENTRIES


WHERE JOB_QUEUE_LIBRARY = 'APP1' AND JOB_QUEUE_NAME = 'BATCHJQ';

1070 IBM i: Performance and Query Optimization


JOB_QUEUE_INFO view
The JOB_QUEUE_INFO view returns one row for each job queue.
The values returned for the columns in the view are similar to the values returned by the Work with Job
Queue (WRKJOBQ) CL command and the Retrieve Job Queue Information (QSPRJOBQ) API.
Authorization: The caller must have:
• *EXECUTE authority to the job queue library, and
– *READ authority to the job queue, or
– *SPLCTL special authority, or
– *JOBCTL special authority and the job queue is defined with OPRCTL(*YES).
The following table describes the columns in the view. The system name is JOBQ_INFO. The schema is
QSYS2.
Table 272. JOB_QUEUE_INFO view

Column Name System Column Name Data Type Description

JOB_QUEUE_NAME JOBQ VARCHAR(10) The name of the job queue.

JOB_QUEUE_LIBRARY JOBQ_LIB VARCHAR(10) The name of the library that contains the job
queue.

JOB_QUEUE_STATUS STATUS VARCHAR(8) The status of the job queue.

HELD The queue is held.

RELEASED The queue is released.

NUMBER_OF_JOBS JOBS INTEGER The number of jobs in the queue.

SUBSYSTEM_NAME SUB_NAME VARCHAR(10) The name of the subsystem that can receive jobs
Nullable from this job queue.
Contains the null value if this job queue is not
associated with an active subsystem.

SUBSYSTEM_LIBRARY_NAME SUBLIB_NAM VARCHAR(10) The library in which the subsystem description


Nullable resides.
Contains the null value if this job queue is not
associated with an active subsystem.

SEQUENCE_NUMBER SEQNO INTEGER The job queue entry sequence number. The
Nullable subsystem uses this number to determine the
order in which job queues are processed. Jobs
from the queue with the lowest sequence number
are processed first.
Contains the null value if this job queue is not
associated with an active subsystem.

MAXIMUM_ACTIVE_JOBS MAX_JOBS INTEGER The maximum number of jobs that can be active
Nullable at the same time through this job queue entry.
A value of -1 indicates *NOMAX, no maximum
number of jobs is defined.
Contains the null value if this job queue is not
associated with an active subsystem.

ACTIVE_JOBS ACT_JOBS INTEGER The current number of jobs that are active that
Nullable came through this job queue entry.
Contains the null value if this job queue is not
associated with an active subsystem.

HELD_JOBS HELD_JOBS INTEGER The current number of jobs that are in


*HELD status. This is the sum of the 10
HELD_JOBS_PRIORITY_n columns.

RELEASED_JOBS RLS_JOBS INTEGER The current number of jobs that are in


*RELEASED status. This is the sum of the 10
RELEASED_JOBS_PRIORITY_n columns.

SCHEDULED_JOBS SCHED_JOBS INTEGER The current number of jobs that are in


*SCHEDULED status. This is the sum of the 10
SCHEDULED_JOBS_PRIORITY_n columns.

Database performance and query optimization 1071


Table 272. JOB_QUEUE_INFO view (continued)

Column Name System Column Name Data Type Description

TEXT_DESCRIPTION TEXT VARCHAR(50) Text that describes the job queue.


Nullable Contains the null value if there is no text
description for the job queue.

OPERATOR_CONTROLLED OPR_CTRL VARCHAR(4) Whether users with job control authority are
allowed to control this job queue and manage
the jobs on the queue. Users have job control
authority if SPCAUT(*JOBCTL) is specified in their
user profile.

*NO This queue and its jobs cannot be


controlled by users with job control
authority unless they also have other
special authority.

*YES Users with job control authority can


control the queue and manage the jobs
on the queue.

AUTHORITY_TO_CHECK ALL_AUTH VARCHAR(7) Whether the user must be the owner of the
queue in order to control the queue by holding or
releasing the queue.

*DTAAUT Any user with *READ, *ADD, or


*DELETE authority to the job queue
can control the queue.

*OWNER Only the owner of the job queue can


control the queue.

MAXIMUM_ACTIVE_JOBS_ MAXIMUM1 INTEGER The maximum number of priority 1 jobs that can
PRIORITY_1 Nullable be active at the same time. A value of -1 indicates
*NOMAX, no maximum number of jobs.
Contains the null value if this job queue is not
associated with an active subsystem.

MAXIMUM_ACTIVE_JOBS_ MAXIMUM2 INTEGER The maximum number of priority 2 jobs that can
PRIORITY_2 Nullable be active at the same time. A value of -1 indicates
*NOMAX, no maximum number of jobs.
Contains the null value if this job queue is not
associated with an active subsystem.

MAXIMUM_ACTIVE_JOBS_ MAXIMUM3 INTEGER The maximum number of priority 3 jobs that can
PRIORITY_3 Nullable be active at the same time. A value of -1 indicates
*NOMAX, no maximum number of jobs.
Contains the null value if this job queue is not
associated with an active subsystem.

MAXIMUM_ACTIVE_JOBS_ MAXIMUM4 INTEGER The maximum number of priority 4 jobs that can
PRIORITY_4 Nullable be active at the same time. A value of -1 indicates
*NOMAX, no maximum number of jobs.
Contains the null value if this job queue is not
associated with an active subsystem.

MAXIMUM_ACTIVE_JOBS_ MAXIMUM5 INTEGER The maximum number of priority 5 jobs that can
PRIORITY_5 Nullable be active at the same time. A value of -1 indicates
*NOMAX, no maximum number of jobs.
Contains the null value if this job queue is not
associated with an active subsystem.

MAXIMUM_ACTIVE_JOBS_ MAXIMUM6 INTEGER The maximum number of priority 6 jobs that can
PRIORITY_6 Nullable be active at the same time. A value of -1 indicates
*NOMAX, no maximum number of jobs.
Contains the null value if this job queue is not
associated with an active subsystem.

MAXIMUM_ACTIVE_JOBS_ MAXIMUM7 INTEGER The maximum number of priority 7 jobs that can
PRIORITY_7 Nullable be active at the same time. A value of -1 indicates
*NOMAX, no maximum number of jobs.
Contains the null value if this job queue is not
associated with an active subsystem.

1072 IBM i: Performance and Query Optimization


Table 272. JOB_QUEUE_INFO view (continued)

Column Name System Column Name Data Type Description

MAXIMUM_ACTIVE_JOBS_ MAXIMUM8 INTEGER The maximum number of priority 8 jobs that can
PRIORITY_8 Nullable be active at the same time. A value of -1 indicates
*NOMAX, no maximum number of jobs.
Contains the null value if this job queue is not
associated with an active subsystem.

MAXIMUM_ACTIVE_JOBS_ MAXIMUM9 INTEGER The maximum number of priority 9 jobs that can
PRIORITY_9 Nullable be active at the same time. A value of -1 indicates
*NOMAX, no maximum number of jobs.
Contains the null value if this job queue is not
associated with an active subsystem.

ACTIVE_JOBS_PRIORITY_0 ACTIVE0 INTEGER The number of priority 0 jobs that are active.
Nullable Contains the null value if this job queue is not
associated with an active subsystem.

ACTIVE_JOBS_PRIORITY_1 ACTIVE1 INTEGER The number of priority 1 jobs that are active.
Nullable Contains the null value if this job queue is not
associated with an active subsystem.

ACTIVE_JOBS_PRIORITY_2 ACTIVE2 INTEGER The number of priority 2 jobs that are active.
Nullable Contains the null value if this job queue is not
associated with an active subsystem.

ACTIVE_JOBS_PRIORITY_3 ACTIVE3 INTEGER The number of priority 3 jobs that are active.
Nullable Contains the null value if this job queue is not
associated with an active subsystem.

ACTIVE_JOBS_PRIORITY_4 ACTIVE4 INTEGER The number of priority 4 jobs that are active.
Nullable Contains the null value if this job queue is not
associated with an active subsystem.

ACTIVE_JOBS_PRIORITY_5 ACTIVE5 INTEGER The number of priority 5 jobs that are active.
Nullable Contains the null value if this job queue is not
associated with an active subsystem.

ACTIVE_JOBS_PRIORITY_6 ACTIVE6 INTEGER The number of priority 6 jobs that are active.
Nullable Contains the null value if this job queue is not
associated with an active subsystem.

ACTIVE_JOBS_PRIORITY_7 ACTIVE7 INTEGER The number of priority 7 jobs that are active.
Nullable Contains the null value if this job queue is not
associated with an active subsystem.

ACTIVE_JOBS_PRIORITY_8 ACTIVE8 INTEGER The number of priority 8 jobs that are active.
Nullable Contains the null value if this job queue is not
associated with an active subsystem.

ACTIVE_JOBS_PRIORITY_9 ACTIVE9 INTEGER The number of priority 9 jobs that are active.
Nullable Contains the null value if this job queue is not
associated with an active subsystem.

RELEASED_JOBS_PRIORITY_0 RELEASED0 INTEGER The number of priority 0 jobs currently sitting on


the job queue in *RELEASED status.

RELEASED_JOBS_PRIORITY_1 RELEASED1 INTEGER The number of priority 1 jobs currently sitting on


the job queue in *RELEASED status.

RELEASED_JOBS_PRIORITY_2 RELEASED2 INTEGER The number of priority 2 jobs currently sitting on


the job queue in *RELEASED status.

RELEASED_JOBS_PRIORITY_3 RELEASED3 INTEGER The number of priority 3 jobs currently sitting on


the job queue in *RELEASED status.

RELEASED_JOBS_PRIORITY_4 RELEASED4 INTEGER The number of priority 4 jobs currently sitting on


the job queue in *RELEASED status.

RELEASED_JOBS_PRIORITY_5 RELEASED5 INTEGER The number of priority 5 jobs currently sitting on


the job queue in *RELEASED status.

RELEASED_JOBS_PRIORITY_6 RELEASED6 INTEGER The number of priority 6 jobs currently sitting on


the job queue in *RELEASED status.

Database performance and query optimization 1073


Table 272. JOB_QUEUE_INFO view (continued)

Column Name System Column Name Data Type Description

RELEASED_JOBS_PRIORITY_7 RELEASED7 INTEGER The number of priority 7 jobs currently sitting on


the job queue in *RELEASED status.

RELEASED_JOBS_PRIORITY_8 RELEASED8 INTEGER The number of priority 8 jobs currently sitting on


the job queue in *RELEASED status.

RELEASED_JOBS_PRIORITY_9 RELEASED9 INTEGER The number of priority 9 jobs currently sitting on


the job queue in *RELEASED status.

SCHEDULED_JOBS_PRIORITY_0 SCHEDULED0 INTEGER The number of priority 0 jobs currently sitting on


the job queue in *SCHEDULED status.

SCHEDULED_JOBS_PRIORITY_1 SCHEDULED1 INTEGER The number of priority 1 jobs currently sitting on


the job queue in *SCHEDULED status.

SCHEDULED_JOBS_PRIORITY_2 SCHEDULED2 INTEGER The number of priority 2 jobs currently sitting on


the job queue in *SCHEDULED status.

SCHEDULED_JOBS_PRIORITY_3 SCHEDULED3 INTEGER The number of priority 3 jobs currently sitting on


the job queue in *SCHEDULED status.

SCHEDULED_JOBS_PRIORITY_4 SCHEDULED4 INTEGER The number of priority 4 jobs currently sitting on


the job queue in *SCHEDULED status.

SCHEDULED_JOBS_PRIORITY_5 SCHEDULED5 INTEGER The number of priority 5 jobs currently sitting on


the job queue in *SCHEDULED status.

SCHEDULED_JOBS_PRIORITY_6 SCHEDULED6 INTEGER The number of priority 6 jobs currently sitting on


the job queue in *SCHEDULED status.

SCHEDULED_JOBS_PRIORITY_7 SCHEDULED7 INTEGER The number of priority 7 jobs currently sitting on


the job queue in *SCHEDULED status.

SCHEDULED_JOBS_PRIORITY_8 SCHEDULED8 INTEGER The number of priority 8 jobs currently sitting on


the job queue in *SCHEDULED status.

SCHEDULED_JOBS_PRIORITY_9 SCHEDULED9 INTEGER The number of priority 9 jobs currently sitting on


the job queue in *SCHEDULED status.

HELD_JOBS_PRIORITY_0 HELD0 INTEGER The number of priority 0 jobs currently sitting on


the job queue in *HELD status.

HELD_JOBS_PRIORITY_1 HELD1 INTEGER The number of priority 1 jobs currently sitting on


the job queue in *HELD status.

HELD_JOBS_PRIORITY_2 HELD2 INTEGER The number of priority 2 jobs currently sitting on


the job queue in *HELD status.

HELD_JOBS_PRIORITY_3 HELD3 INTEGER The number of priority 3 jobs currently sitting on


the job queue in *HELD status.

HELD_JOBS_PRIORITY_4 HELD4 INTEGER The number of priority 4 jobs currently sitting on


the job queue in *HELD status.

HELD_JOBS_PRIORITY_5 HELD5 INTEGER The number of priority 5 jobs currently sitting on


the job queue in *HELD status.

HELD_JOBS_PRIORITY_6 HELD6 INTEGER The number of priority 6 jobs currently sitting on


the job queue in *HELD status.

HELD_JOBS_PRIORITY_7 HELD7 INTEGER The number of priority 7 jobs currently sitting on


the job queue in *HELD status.

HELD_JOBS_PRIORITY_8 HELD8 INTEGER The number of priority 8 jobs currently sitting on


the job queue in *HELD status.

HELD_JOBS_PRIORITY_9 HELD9 INTEGER The number of priority 9 jobs currently sitting on


the job queue in *HELD status.

Example
• Examine the job queues with the largest number of active jobs

SELECT * FROM QSYS2.JOB_QUEUE_INFO


WHERE ACTIVE_JOBS IS NOT NULL
ORDER BY NUMBER_OF_JOBS DESC;

1074 IBM i: Performance and Query Optimization


MEMORY_POOL table function
The MEMORY_POOL table function returns one row for every pool.
The information returned is similar to the detail seen from the Work System Status (WRKSYSSTS)
command.
Authorization: None required.

MEMORY_POOL ( )
reset_statistics
RESET_STATISTICS =>

The schema is QSYS2.

reset_statistics A character or graphic string expression that contains a value of YES or NO.
If this parameter has a value of YES, statistics are reset such that the time of this query
execution is used as the new baseline. The columns that contain this statistical data
have names that are prefixed with ELAPSED_. Future invocations of MEMORY_POOL
within this connection will return statistical detail relative to the new baseline. If this
parameter has a value of NO, statistics are not reset for the invocation. If this parameter
is not specified, the default is NO.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 273. MEMORY_POOL table function

Column Name Data Type Description

SYSTEM_POOL_ID INTEGER The system-related pool identifier for each of the system storage
pools that currently has main storage allocated to it.

POOL_NAME VARCHAR(10) The name of this storage pool. The name may be a number, in which
case it is a private pool associated with a subsystem, or one of the
following special values.

*MACHINE The machine pool.

*BASE The base system pool, which can be shared with


other subsystems.

*INTERACT The shared pool used for the QINTER subsystem.

*SPOOL The shared pool used for spooled writers.

*SHRPOOLx A shared pool.

CURRENT_SIZE DECIMAL(20,2) The amount of main storage, in megabytes, in the pool.

RESERVED_SIZE DECIMAL(10,2) The amount of storage, in megabytes, in the pool reserved for system
use (for example, for save/restore operations).

DEFINED_SIZE DECIMAL(20,2) The size of the pool, in megabytes, as defined in the shared pool,
subsystem description, or system value QMCHPOOL. Contains the null
value for a pool without a defined size.

MAXIMUM_ACTIVE_THREADS INTEGER The maximum number of threads that can be active in the pool at any
one time.

CURRENT_THREADS INTEGER The number of threads currently using the pool.

CURRENT_INELIGIBLE_THREADS INTEGER The number of ineligible threads in the pool.

STATUS VARCHAR(8) The status of the pool.

ACTIVE Pool is currently active.

INACTIVE Pool is currently not active.

SUBSYSTEM_LIBRARY_NAME VARCHAR(10) The library containing the subsystem name. Contains the null value for
shared pools.

Database performance and query optimization 1075


Table 273. MEMORY_POOL table function (continued)

Column Name Data Type Description

SUBSYSTEM_NAME VARCHAR(10) The subsystem with which this storage pool is associated. Contains
the null value for shared pools.

DESCRIPTION VARCHAR(50) The description of the shared pool. Contains the null value for private
pools or if a description does not exist for a shared pool.

PAGING_OPTION VARCHAR(10) Whether the system will dynamically adjust the paging characteristics
of the storage pool for optimum performance.

*FIXED The system does not dynamically adjust the paging


characteristics.

*CALC The system dynamically adjusts the paging


characteristics.

USRDFN The system does not dynamically adjust the paging


characteristics for the storage pool but uses values that
have been defined through the QWCCHGTN API.

ELAPSED_TIME INTEGER The time, in seconds, since the measurement start time.

ELAPSED_DATABASE_FAULTS DECIMAL(10,1) The rate, in page faults per second, of database page faults against
pages containing either database access paths or data.

ELAPSED_NON_DATABASE_FAULTS DECIMAL(10,1) The rate, in page faults per second, of nondatabase page faults
against pages other than those designated as database pages.

ELAPSED_TOTAL_FAULTS DECIMAL(10,1) The rate, in page faults per second, of database faults and non-
database faults.

ELAPSED_DATABASE_PAGES DECIMAL(10,1) The rate, in pages per second, at which database pages are brought
into the storage pool.

ELAPSED_NON_DATABASE_PAGES DECIMAL(10,1) The rate in pages per second at which nondatabase pages are brought
into the storage pool.

ELAPSED_ACTIVE_TO_WAIT DECIMAL(10,1) The rate, in transitions per minute, of transitions of threads from an
active condition to a waiting condition.

ELAPSED_WAIT_TO_INELIGIBLE DECIMAL(10,1) The rate, in transitions per minute, of transitions of threads from a
waiting condition to an ineligible condition.

ELAPSED_ACTIVE_TO_INELIGIBLE DECIMAL(10,1) The rate, in transitions per minute, of transitions of threads from an
active condition to an ineligible condition.

TUNING_PRIORITY INTEGER The priority of the shared storage pool used by the system when
making automatic performance adjustments. Contains the null value
for private pools defined in subsystem descriptions.

TUNING_MINIMUM_SIZE DECIMAL(10,2) The minimum amount of storage to allocate to the shared storage pool
(as a percentage of total main storage). Contains the null value for
private pools defined in subsystem descriptions.

TUNING_MAXIMUM_SIZE DECIMAL(10,2) The maximum amount of storage to allocate to the shared storage
pool (as a percentage of total main storage). Contains the null value
for private pools defined in subsystem descriptions.

TUNING_MINIMUM_FAULTS DECIMAL(10,2) The maximum page faults per second to use as a guideline for the
shared storage pool. Contains the null value for private pools defined
in subsystem descriptions.

TUNING_MAXIMUM_FAULTS DECIMAL(10,2) The minimum page faults per second to use as a guideline for the
shared storage pool. Contains the null value for private pools defined
in subsystem descriptions.

TUNING_THREAD_FAULTS DECIMAL(10,2) The page faults per second for each active thread to use as a guideline
for the shared storage pool. Contains the null value for private pools
defined in subsystem descriptions.

TUNING_MINIMUM_ACTIVITY DECIMAL(10,2) The minimum value that the shared pool's activity level can be set to
by the performance adjuster when the QPFRADJ system value is set to
2 or 3. Contains the null value for private pools defined in subsystem
descriptions.

TUNING_MAXIMUM_ACTIVITY DECIMAL(10,2) The maximum value that the shared pool's activity level can be set to
by the performance adjuster when the QPFRADJ system value is set to
2 or 3. Contains the null value for private pools defined in subsystem
descriptions.

Example

1076 IBM i: Performance and Query Optimization


Return all available pool information, both private and shared, active and inactive. Specify to reset all the
elapsed values to 0.

SELECT * FROM TABLE(QSYS2.MEMORY_POOL(RESET_STATISTICS=>'YES')) X;

MEMORY_POOL_INFO view
The MEMORY_POOL_INFO view returns one row for every active pool.
The information returned is similar to the detail seen from the Work System Status (WRKSYSSTS)
command. It does not reset the statistical columns; to do this, use the associated table function,
MEMORY_POOL.
Authorization: None required.
The following table describes the columns in the view. The system name is POOL_INFO. The schema is
QSYS2.
Table 274. MEMORY_POOL_INFO view

Column Name System Column Name Data Type Description

SYSTEM_POOL_ID POOL_ID INTEGER The system-related pool identifier for each of the system
storage pools that currently has main storage allocated to it.

POOL_NAME POOL_NAME VARCHAR(10) The name of this storage pool. The name may be a number, in
which case it is a private pool associated with a subsystem, or
one of the following special values.

*MACHINE The machine pool.

*BASE The base system pool, which can be shared


with other subsystems.

*INTERACT The shared pool used for the QINTER


subsystem.

*SPOOL The shared pool used for spooled writers.

*SHRPOOLx A shared pool.

CURRENT_SIZE CURR_SIZE DECIMAL(20,2) The amount of main storage, in megabytes, in the pool.

RESERVED_SIZE RSVD_SIZE DECIMAL(10,2) The amount of storage, in megabytes, in the pool reserved for
system use (for example, for save/restore operations).

DEFINED_SIZE DFND_SIZE DECIMAL(20,2) The size of the pool, in megabytes, as defined in the shared
pool, subsystem description, or system value QMCHPOOL.
Contains the null value for a pool without a defined size.

MAXIMUM_ACTIVE_THREADS MAX_THREAD INTEGER The maximum number of threads that can be active in the pool
at any one time.

CURRENT_THREADS CURR_THRD INTEGER The number of threads currently using the pool.

CURRENT_INELIGIBLE_THREADS INEL_THRD INTEGER The number of ineligible threads in the pool.

SUBSYSTEM_LIBRARY_NAME SUBLIB_NAM VARCHAR(10) The library containing the subsystem name. Contains the null
value for shared pools.
Nullable

SUBSYSTEM_NAME SUB_NAME VARCHAR(10) The subsystem with which this storage pool is associated.
Contains the null value for shared pools.
Nullable

DESCRIPTION DESC VARCHAR(50) The description of the shared pool. Contains the null value for
private pools or if a description does not exist for a shared pool.
Nullable

Database performance and query optimization 1077


Table 274. MEMORY_POOL_INFO view (continued)

Column Name System Column Name Data Type Description

PAGING_OPTION PAGE_OPT VARCHAR(10) Whether the system will dynamically adjust the paging
characteristics of the storage pool for optimum performance.

*FIXED The system does not dynamically adjust the paging


characteristics.

*CALC The system dynamically adjusts the paging


characteristics.

USRDFN The system does not dynamically adjust the paging


characteristics for the storage pool but uses values
that have been defined through the QWCCHGTN
API.

ELAPSED_TIME ELAP_TIME INTEGER The time, in seconds, since the measurement start time.

ELAPSED_DATABASE_FAULTS ELAP_DBF DECIMAL(10,1) The rate, in page faults per second, of database page faults
against pages containing either database access paths or data.

ELAPSED_NON_DATABASE_FAULTS ELAP_NDBF DECIMAL(10,1) The rate, in page faults per second, of nondatabase page faults
against pages other than those designated as database pages.

ELAPSED_TOTAL_FAULTS ELAP_TOTF DECIMAL(10,1) The rate, in page faults per second, of database faults and
non-database faults.

ELAPSED_DATABASE_PAGES ELAP_DBP DECIMAL(10,1) The rate, in pages per second, at which database pages are
brought into the storage pool.

ELAPSED_NON_DATABASE_PAGES ELAP_NDBP DECIMAL(10,1) The rate in pages per second at which nondatabase pages are
brought into the storage pool.

ELAPSED_ACTIVE_TO_WAIT ELAP_ATW DECIMAL(10,1) The rate, in transitions per minute, of transitions of threads
from an active condition to a waiting condition.

ELAPSED_WAIT_TO_INELIGIBLE ELAP_WTI DECIMAL(10,1) The rate, in transitions per minute, of transitions of threads
from a waiting condition to an ineligible condition.

ELAPSED_ACTIVE_TO_INELIGIBLE ELAP_ATI DECIMAL(10,1) The rate, in transitions per minute, of transitions of threads
from an active condition to an ineligible condition.

TUNING_PRIORITY TUN_PRIOR INTEGER The priority of the shared storage pool used by the system
when making automatic performance adjustments. Contains
Nullable the null value for private pools defined in subsystem
descriptions.

TUNING_MINIMUM_SIZE TUN_MIN_SZ DECIMAL(10,2) The minimum amount of storage to allocate to the shared
storage pool (as a percentage of total main storage). Contains
Nullable the null value for private pools defined in subsystem
descriptions.

TUNING_MAXIMUM_SIZE TUN_MAX_SZ DECIMAL(10,2) The maximum amount of storage to allocate to the shared
storage pool (as a percentage of total main storage). Contains
Nullable the null value for private pools defined in subsystem
descriptions.

TUNING_MINIMUM_FAULTS TUN_MIN_FT DECIMAL(10,2) The maximum page faults per second to use as a guideline
for the shared storage pool. Contains the null value for private
Nullable pools defined in subsystem descriptions.

TUNING_MAXIMUM_FAULTS TUN_MAX_FT DECIMAL(10,2) The minimum page faults per second to use as a guideline
for the shared storage pool. Contains the null value for private
Nullable pools defined in subsystem descriptions.

TUNING_THREAD_FAULTS TUN_THR_FT DECIMAL(10,2) The page faults per second for each active thread to use as a
guideline for the shared storage pool. Contains the null value
Nullable for private pools defined in subsystem descriptions.

TUNING_MINIMUM_ACTIVITY TUN_MIN_AC DECIMAL(10,2) The minimum value that the shared pool's activity level can be
set to by the performance adjuster when the QPFRADJ system
Nullable value is set to 2 or 3. Contains the null value for private pools
defined in subsystem descriptions.

TUNING_MAXIMUM_ACTIVITY TUN_MAX_AC DECIMAL(10,2) The maximum value that the shared pool's activity level can be
set to by the performance adjuster when the QPFRADJ system
Nullable value is set to 2 or 3. Contains the null value for private pools
defined in subsystem descriptions.

Example

1078 IBM i: Performance and Query Optimization


Return all active pool information.

SELECT * FROM QSYS2.MEMORY_POOL_INFO;

OBJECT_LOCK_INFO view
The OBJECT_LOCK_INFO view returns one row for every lock held for every object on the partition in
*SYSBAS and in the current thread's ASP group.
The values returned for the columns in the view are closely related to the values returned by Retrieve
Lock Information API and Retrieve Lock Request Information API. Refer to the APIs for more detailed
information.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the object, and
• *OBJOPR and *READ authority to the database file
The following table describes the columns in the view. The system name is OBJ_LOCK. The schema is
QSYS2.
Table 275. OBJECT_LOCK_INFO view

Column Name System Column Name Data Type Description

OBJECT_SCHEMA OSCHEMA VARCHAR(128) The name of the schema containing the object.

OBJECT_NAME NAME VARCHAR(128) The name of the object.

SYSTEM_OBJECT_SCHEMA SYS_DNAME VARCHAR(10) The system library name of the object.

SYSTEM_OBJECT_NAME SYS_ONAME VARCHAR(10) The system name of the object

SYSTEM_TABLE_MEMBER SYS_MNAME VARCHAR(10) The name of the member that is locked in the file.

Nullable Contains the null value if the lock information is not for a
member.

OBJECT_TYPE OBJTYPE VARCHAR(8) The system object type of the locked object.

SQL_OBJECT_TYPE SQLTYPE VARCHAR(9) The SQL type of the object. Values are:

Nullable • ALIAS
• FUNCTION
• INDEX
• PACKAGE
• PROCEDURE
• ROUTINE
• SEQUENCE
• TABLE
• TRIGGER
• TYPE
• VARIABLE
• VIEW
• XSR
Contains the null value if the object is not an SQL object.

ASP_NUMBER ASPNUM INTEGER The numeric identifier of the ASP containing the object that is
locked. A value of 0 is returned for *SYSBAS.

ASPGRP ASPGRP VARCHAR(10) The name of the ASP device containing the object that is locked.
Can contain the special value of *SYSBAS.

Database performance and query optimization 1079


Table 275. OBJECT_LOCK_INFO view (continued)

Column Name System Column Name Data Type Description

MEMBER_LOCK_TYPE LOCK_TYPE VARCHAR(10) The type of lock that is held.

Nullable ACCESSPATH Lock on the access path used to access the


member's data.

DATA Lock on the actual data within the member.

MEMBER Lock on the member control block.

Contains the null value if the lock information is not for a


member.

LOCK_STATE LOCK_STATE VARCHAR(7) The lock condition for the object or member.

*EXCL Lock exclusive no read.

*EXCLRD Lock exclusive allow read.

*SHRNUP Lock shared no update.

*SHRRD Lock shared for read.

*SHRUPD Lock shared for update.

LOCK_STATUS STATUS VARCHAR(9) The status of the lock.

HELD The lock is currently held by the job.

REQUESTED The job has a lock request outstanding for the


object.

WAITING The job is waiting for the lock.

LOCK_SCOPE LOCK_SCOPE VARCHAR(10) The scope of the lock. Values are:


• JOB
• LOCK SPACE
• THREAD

JOB_NAME JOB_NAME VARCHAR(28) The qualified job name.

Nullable Contains the null value when the LOCK_SCOPE column value is
LOCK SPACE.

THREAD_ID THREAD_ID BIGINT The thread that is associated with the lock.

Nullable • If a held lock is job scoped, returns the null value. If a held
lock is thread scoped, contains the identifier for the thread
holding the lock.
• If the scope of the lock is to the lock space and the lock is not
held, contains the identifier of the thread requesting the lock.
• If the lock is requested but not yet available, contains the
identifier of the thread requesting the lock.

LOCK_SPACE_ID LOCKID BINARY(20) When the LOCK_SCOPE column value is LOCK SPACE and the
lock is held, contains the lock space ID value of the lock space
Nullable that holds the lock. If the lock is being waited on by a thread,
contains the lock space ID value for which the lock is being
waited on.
Otherwise, contains the null value.

LOCK_COUNT LOCK_COUNT INTEGER The number of identical locks held.

PROGRAM_LIBRARY_NAME PROGLIB VARCHAR(10) The name of the library containing the program or service
program.
Nullable
Contains the null value if the lock holder information is not
available.

PROGRAM_NAME PROGNAME VARCHAR(10) The name of the program holding the lock. This can be any type
of program object, including objects of type *PGM and *SRVPGM.
Nullable
Contains the null value if the lock holder information is not
available.

MODULE_NAME_LIBRARY MODLIB VARCHAR(10) The library containing the module.

Nullable Contains the null value if the lock holder information is not
available or if the program is not an ILE program.

1080 IBM i: Performance and Query Optimization


Table 275. OBJECT_LOCK_INFO view (continued)

Column Name System Column Name Data Type Description

MODULE_NAME MODNAME VARCHAR(10) The module containing the ILE procedure.

Nullable Contains the null value if the lock holder information is not
available or if the program is not an ILE program.

PROCEDURE_NAME PROCNAME VARCHAR(4096) The name of the procedure.

Nullable Contains the null value if the lock holder information is not
available.

STATEMENT_ID STMTID CHAR(10) The high-level language statement identifier. For a character
representation of a number, the number is right-adjusted and
Nullable padded on the left with zeros (for example, '0000000246').
Contains the null value if the lock holder information is not
available.

MACHINE_INSTRUCTION INSTRUCT INTEGER The current machine instruction number in the program.

Nullable Contains the null value if the lock holder information is not
available or if it is an ILE procedure.

Example
Find all the jobs holding object locks over the SALES table:

SELECT * FROM QSYS2.OBJECT_LOCK_INFO


WHERE SYSTEM_OBJECT_SCHEMA = 'TOYSTORE' AND
SYSTEM_OBJECT_NAME = 'SALES'

OPEN_FILES table function


The OPEN_FILES table function returns a list of files (*FILE objects) that are open in all threads for a job.
This information is similar to what can be accessed through the Display Job (DSPJOB) CL command and
by the List Open Files (QDMLOPNF) API.
Authorization: None required to see information for jobs where the caller's user profile is the same as the
job user identity of the job for which the information is being returned. To see information for other jobs,
the caller must have *JOBCTL special authority.

OPEN_FILES ( job-name )
JOB_NAME =>

The schema is QSYS2.

job-name A character or graphic string expression that identifies the qualified name of a job. The
special value of '*' indicates the current job.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 276. OPEN_FILES table function

Column Name Data Type Description

LIBRARY_NAME VARCHAR(10) The name of the library that contains the open file.
Contains the null value if the file is an inline data file.

FILE_NAME VARCHAR(10) The name of the file that is open. For an unnamed inline data file, contains
the value QINLINE.

Database performance and query optimization 1081


Table 276. OPEN_FILES table function (continued)

Column Name Data Type Description

FILE_TYPE VARCHAR(7) The type of file that is open.

BSCF Binary Synchronous Communications (BSC) file

CMNF Communications file

DDMF Distributed Data Management file

DKTF Diskette file (spooled and non-spooled)

DSPF Display file

ICFF Intersystem Communications Function file

LF Logical file

MXDF Mixed file

PF Physical file

PRTF Printer file (spooled and non-spooled)

SAVF Save file

TAPF Tape file

*INLINE Inline data file

MEMBER_NAME VARCHAR(10) If FILE_TYPE is physical (PF) or logical (LF), the name of the database
member. If multiple member processing is being performed, the value is
*ALL.
Contains the null value for a DDM file, an inline data file, and a device file.

DEVICE_NAME VARCHAR(10) The name of the last program device used for an I/O operation if FILE_TYPE
is a device file (BSCF, CMNF, DKTF, DSPF, ICFF, MXDF, PRTF, SAVF, or TAPF).
If the file is a spooled file, the value is *SPOOL.
Contains the null value for a device file when no I/O operation has been
performed, a database physical or logical file, a DDM file, and an inline data
file.

RECORD_FORMAT VARCHAR(10) The name of the last record format that was used for an I/O operation to the
file.
Contains the null value if no record format name was used or no I/O
operations have been performed.

ACTIVATION_GROUP_NAME VARCHAR(10) The name of the activation group to which the open file is scoped.

*DFTACTGRP The file is scoped to the default activation group.

*NEW The file is scoped to a *NEW activation group.

Contains the null value for a file scoped to the job, not a specific activation
group.

ACTIVATION_GROUP_NUMBER INTEGER The number of the activation group to which the open file is scoped.
Contains the null value for a file scoped to the job, not a specific activation
group.

THREAD_ID BIGINT The thread handle assigned by the system which identifies the thread in
which the file was opened.

OPEN_OPTION VARCHAR(6) The type of open operation that was performed.

ALL The file was opened for all operations (input, output, update,
and delete).

INPUT The file was opened for input operations only.

OUTPUT The file was opened for output operations only.

SHARED_OPENS BIGINT The number of times the file was opened for shared processing.
Contains the null value for open operations that are not shared.

WRITE_COUNT BIGINT The number of successful write operations. If record blocking is not in effect
for the file, this is the number of records. If record blocking is in effect for
the file, this is the number of record blocks.

READ_COUNT BIGINT Number of successful read operations. If record blocking is not in effect for
the file, this is the number of records. If record blocking is in effect for the
file, this is the number of record blocks.

1082 IBM i: Performance and Query Optimization


Table 276. OPEN_FILES table function (continued)

Column Name Data Type Description

WRITE_READ_COUNT BIGINT The number of successful write/read operations.

OTHER_IO_COUNT BIGINT Number of successful I/O operations of the following types:


• update
• delete
• change end-of-data
• force end-of-data
• force end-of-volume
• release record lock
• acquire or release program device

RELATIVE_RECORD_NUMBER BIGINT Relative record number of the last record referred to by an I/O or open
operation for database files.
Contains the null value for nondatabase files and database files on which no
I/O operations have been performed.

IASP_NAME VARCHAR(10) The auxiliary storage pool (ASP) device name where the library is stored.
If the library is in the system ASP or one of the basic user ASPs, contains
*SYSBAS.
Contains the null value if the file is an inline data file or if the name of the
ASP device cannot be determined.

IASP_NUMBER INTEGER The number of the auxiliary storage pool (ASP) from which the system
allocates storage for the library.
Contains the null value if the file is an inline data file or if the number of the
ASP device cannot be determined.

Example
• List all the database files that are open for job 429467/QUSER/QZDASOINIT.

SELECT * FROM TABLE(QSYS2.OPEN_FILES('429467/QUSER/QZDASOINIT'))


WHERE FILE_TYPE IN ('PF', 'LF');

PRESTART_JOB_INFO view
The PRESTART_JOB_INFO view returns information about prestart jobs.
The values returned for the columns in the view are closely related to the values returned by the Display
Prestart Job Entries panel accessed through the DSPSBSD (Display Subsystem Description) CL command
and by the List Subsystem Entries (QWDLSBSE) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the subsystem description, and
• *USE authority to the subsystem description.
The following table describes the columns in the view. The system name is PREJ_INFO. The schema is
QSYS2.
Table 277. PRESTART_JOB_INFO view

Column Name System Column Name Data Type Description

SUBSYSTEM_DESCRIPTION_LIBRARY SBSD_LIB VARCHAR(10) The name of the library in which the subsystem
description resides.

SUBSYSTEM_DESCRIPTION SBSD VARCHAR(10) The name of the subsystem about which


information is being returned.

PRESTART_JOB_PROGRAM_LIBRARY PJ_PGM_LIB VARCHAR(10) The name of the library in which the prestart job
program resides.

PRESTART_JOB_PROGRAM PJ_PGM VARCHAR(10) The program name that is used to match an


incoming request with an available prestart job.

Database performance and query optimization 1083


Table 277. PRESTART_JOB_INFO view (continued)

Column Name System Column Name Data Type Description

SUBSYSTEM_ACTIVE SBS_ACTIVE VARCHAR(3) Whether the subsystem for this prestart job is
active.

NO The status of the subsystem is not


ACTIVE.

YES The status of the subsystem is ACTIVE.

USER_PROFILE USRPRF VARCHAR(10) The name of the user profile under which the
prestart job runs.

PRESTART_JOB_NAME PJ_NAME VARCHAR(10) The name of the prestart job.

JOB_DESCRIPTION_LIBRARY JOBDLIB VARCHAR(10) The name of the library in which the job
description for the prestart job entry resides.
Nullable
Contains the null value if JOB_DESCRIPTION is
*USRPRF.

JOB_DESCRIPTION JOBD VARCHAR(10) The name of the job description that is used for
the prestart job entry. Can contain the following
special value:

*USRPRF The job description that has the


same name as the user profile that
is used.

START_JOBS START_JOBS VARCHAR(3) Whether the prestart jobs are started at the time
the subsystem is started.

NO The prestart jobs are not started at the


time the subsystem is started. The Start
Prestart Jobs (STRPJ) command is used
to start these prestart jobs.

YES The prestart jobs are started at the time


the subsystem is started.

INITIAL_JOBS INIT_JOBS INTEGER The initial number of prestart jobs that are started
when the subsystem is started.

THRESHOLD THRESHOLD INTEGER The number at which additional prestart jobs are
started. When the pool of available jobs (jobs
available to service a program start request) is
reduced below this number, more jobs (specified
by ADDITIONAL_JOBS) are started and added to
the available pool. This number is checked after
a prestart job is attached to a procedure start
request.

ADDITIONAL_JOBS ADD_JOBS INTEGER The additional number of prestart jobs that are
started when the number of prestart jobs drops
below the value of THRESHOLD.

MAXIMUM_JOBS MAX_JOBS INTEGER The maximum number of prestart jobs that can be
active at the same time for this prestart job entry.
A value of -1 indicates *NOMAX.

MAXIMUM_USES MAX_USES INTEGER The maximum number of requests that can be


handled by each prestart job in the pool before
the job is ended. A value of -1 indicates *NOMAX.

WAIT_FOR_JOB WAIT VARCHAR(3) Whether requests wait for a prestart job to


become available or are rejected if a prestart job
is not immediately available when the request is
received.

NO Requests are rejected if a prestart job


is not immediately available when the
request is received.

YES Requests wait until there is an available


prestart job, or until a prestart job is
started, to handle the request.

POOL_ID POOL_ID INTEGER The subsystem pool in which the prestart jobs will
run.

1084 IBM i: Performance and Query Optimization


Table 277. PRESTART_JOB_INFO view (continued)

Column Name System Column Name Data Type Description

CLASS_LIBRARY CLASS1_LIB VARCHAR(10) The name of the library in which the first class
resides.

CLASS CLASS1 VARCHAR(10) The name of the first class that the prestart jobs
run under. Jobs start by using the first class that
is specified until the number of jobs specified for
the first class is reached. After the number of jobs
that are specified for the first class is reached,
then jobs are started by using the second class.

CLASS_JOBS CLASS1_JOB INTEGER The maximum number of jobs to run using the
first class. Can contain the following special
values:

-3 The system calculates how many prestart


jobs use this class.
If only one class is specified and -3 is
specified, all of the jobs use that class.
If two classes are specified and -3 is
specified for both, the first class is the
value of MAXIMUM_JOBS divided by two,
and the second class is the value of
MAXIMUM_JOBS minus the value that is
calculated for the first class.
If a specific number of jobs is specified for
either class and -3 is specified for the other
class, the system calculates the difference
between MAXIMUM_JOBS and the specific
number of jobs for the -3 designation.

-4 All of the prestart jobs use the specified


class.

CLASS2_LIBRARY CLASS2_LIB VARCHAR(10) The name of the library in which the second class
resides.
Nullable
Contains the null value if only one class is used.

CLASS2 CLASS2 VARCHAR(10) The second class that the prestart jobs run under.

Nullable Contains the null value if only one class is used.

CLASS2_JOBS CLASS2_JOB INTEGER The maximum number of jobs to run using the
second class. Can contain the following special
Nullable values:

-3 The system calculates how many prestart


jobs use this class.

-4 All of the prestart jobs use the specified


class.

Contains the null value if only one class is used.

RESOURCES_AFFINITY_GROUP RAG VARCHAR(3) Specifies whether the prestart jobs started by this
entry are grouped together having affinity to the
same set of processors and memory.

NO Prestart jobs will not be grouped together.


They will be spread across all the
available system resources.

YES Prestart jobs will be grouped together


such that they will have affinity to the
same system resources.

Database performance and query optimization 1085


Table 277. PRESTART_JOB_INFO view (continued)

Column Name System Column Name Data Type Description

THREAD_RESOURCES_AFFINITY_ T_RAG VARCHAR(7) Specifies whether secondary threads running


GROUP in the prestart jobs are grouped together with
the initial thread, or spread across the system
resources.

GROUP Secondary threads running in the


prestart job will all have affinity
to the same set of processors and
memory as the initial thread.

NOGROUP Secondary threads running in the


prestart job will not necessarily
have affinity to the same set of
processors and memory as the
initial thread. They will be spread
across all the available system
resources.

SYSVAL The thread resources affinity group


and level in the QTHDRSCAFN
system value will be used when the
job starts.

THREAD_RESOURCES_AFFINITY_ T_RAL VARCHAR(6) The degree to which the system tries to


LEVEL maintain the affinity between threads and system
Nullable resources.

HIGH A thread will only use the resources


it has affinity to, and will wait until
they become available if necessary.

NORMAL A thread will use any processor


or memory in the system if the
resources it has affinity to are not
readily available.

Contains the null value when


THREAD_RESOURCES_AFFINITY_GROUP is
SYSVAL.

Example
• List all the prestart job entries in the QUSRWRK subsystem.

SELECT *
FROM QSYS2.PRESTART_JOB_INFO
WHERE SUBSYSTEM_DESCRIPTION_LIBRARY = 'QSYS' AND
SUBSYSTEM_DESCRIPTION = 'QUSRWRK';

PRESTART_JOB_STATISTICS table function


The PRESTART_JOB_STATISTICS table function returns statistics and performance information for an
active prestart job entry in an active subsystem. The information is collected from the time the reset key is
pressed on the Display Active Prestart Jobs (DSPACTPJ) command, from the time the prestart job entry is
started, or from the time RESET_STATISTICS => 'YES' is run for this table function. The prestart job entry
is started when the subsystem starts or when the Start Prestart Jobs (STRPJ) command is used.
This information is similar to what is returned by the Display Active Prestart Jobs (DSPACTPJ) command
and the Retrieve Active Prestart Jobs Status (QWTRAPJS) API.
Authorization: The caller must have:
• *EXECUTE authority to the prestart job's program library.
• *USE authority to the ASP device description, if the subsystem description specifies an ASP group name.
.

1086 IBM i: Performance and Query Optimization


PRESTART_JOB_STATISTICS ( subsystem-name ,
SUBSYSTEM_NAME =>

prestart-job-program-library ,
PRESTART_JOB_PROGRAM_LIBRARY =>

prestart-job-program
PRESTART_JOB_PROGRAM =>

, reset-statistics
RESET_STATISTICS =>

)
, ignore-errors
IGNORE_ERRORS =>

The schema is QSYS2.

subsystem- A character or graphic string expression that contains the name of the active
name subsystem that contains the prestart job entry.
prestart-job- A character or graphic string expression that contains the name of the library where
program-library prestart-job-program is located. Can contain the following special values:

*CURLIB The thread's current library is used to locate prestart-job-program.


*LIBL The library list is used to locate prestart-job-program.

prestart-job- A character or graphic string expression that contains the name of the program that
program identifies the active prestart job entry.
reset-statistics A character or graphic string expression that contains a value of YES or NO to indicate
whether the statistical information should be reset. If this parameter is not specified,
the default is NO.
If the value is YES, the statistics are reset after the information is gathered. The
reset applies to the statistics shown by the Display Active Prestart Jobs (DSPACTPJ)
command as well.

ignore-errors A character or graphic string expression that identifies what to do when an error is
encountered.

NO An error is returned.

YES A warning is returned.


No row is returned when an error is encountered. This is the default.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 278. PRESTART_JOB_STATISTICS view

Column Name Data Type Description

SUBSYSTEM_NAME VARCHAR(10) The name of the active subsystem that contains the prestart job entry.

PRESTART_JOB_PROGRAM_LIBRARY VARCHAR(10) The library where the prestart job program is located.

PRESTART_JOB_PROGRAM VARCHAR(10) The program that identifies the active prestart job entry.

STATUS_TIMESTAMP TIMESTAMP The date and time this active prestart jobs status information was collected.

Database performance and query optimization 1087


Table 278. PRESTART_JOB_STATISTICS view (continued)

Column Name Data Type Description

ELAPSED_TIME INTEGER The time that has elapsed, in seconds, since the last reset date/time.
The value will not reflect elapsed time beyond 10,000 hours. A value of 0
might mean that the elapsed time could not be calculated.

CURRENT_JOBS INTEGER The current number of active jobs associated with the prestart job entry.

AVERAGE_JOBS DECIMAL(10,1) The average number of jobs that have been active since the reset date/time.
This value is based on calculations involving time intervals and is inaccurate if
the system clock was changed while information is being collected.
This value will be recalculated after statistics are reset.

PEAK_JOBS INTEGER The maximum number of jobs that have been active since the reset date/
time.
This value will be recalculated after statistics are reset.

CURRENT_INUSE_JOBS INTEGER The current number of jobs in use.

AVERAGE_INUSE_JOBS DECIMAL(10,1) The average number of jobs in use since the reset date/time. This value is
based on calculations involving time intervals and is inaccurate if the system
clock was changed while information is being collected.
This value will be recalculated after statistics are reset.

PEAK_INUSE_JOBS INTEGER The maximum number of jobs in use since the reset date/time.
This value will be recalculated after statistics are reset.

CURRENT_WAIT_REQUESTS INTEGER The number of requests that are waiting for a prestart job.

AVERAGE_WAIT_REQUESTS DECIMAL(10,1) The average number of requests that have waited for a prestart job since the
reset date/time. This value is based on calculations involving time intervals
and is inaccurate if the system clock was changed while information is being
collected.
This value will be recalculated after statistics are reset.

PEAK_WAIT_REQUESTS INTEGER The maximum number of requests that have waited at one time for an
available prestart job since the reset date/time.
This value will be recalculated after statistics are reset.

AVERAGE_WAIT_TIME DECIMAL(10,1) The average time, in seconds, that requests have waited to be attached to a
prestart job since the reset date/time. This includes requests that wait and
requests that do not wait. This value is based on calculations involving time
intervals and is inaccurate if the system clock was changed while information
is being collected.
This value will be recalculated after statistics are reset.

ACCEPTED_REQUESTS INTEGER The total number of accepted requests since the reset date/time. An
accepted request is one that is either attached immediately to a prestart
job, or is queued because a prestart job is not available.
This value will be recalculated after statistics are reset.

REJECTED_REQUESTS INTEGER The total number of rejected requests since the reset date/time. A request is
rejected if
• *NO is specified for the WAIT parameter on the prestart job entry and
there are no jobs currently available to handle the request.
• *YES is specified for the WAIT parameter and there are more program
start requests than the maximum jobs allowed.
This value will be recalculated after statistics are reset.

Example
List the current statistics for all prestart jobs in the QUSRWRK subsystem. A warning will be issued for
each prestart job returned from PRESTART_JOB_INFO that is not active.

SELECT PJ.PRESTART_JOB_NAME, STAT.*


FROM QSYS2.PRESTART_JOB_INFO PJ,
LATERAL (
SELECT * FROM TABLE
(QSYS2.PRESTART_JOB_STATISTICS(PJ.SUBSYSTEM_DESCRIPTION,
PJ.PRESTART_JOB_PROGRAM_LIBRARY,
PJ.PRESTART_JOB_PROGRAM))) AS STAT

1088 IBM i: Performance and Query Optimization


WHERE PJ.SUBSYSTEM_ACTIVE = 'YES' AND
PJ.SUBSYSTEM_DESCRIPTION = 'QUSRWRK';

RECORD_LOCK_INFO view
The RECORD_LOCK_INFO view returns one row for every record lock for the partition.
The values returned for the columns in the view are closely related to the values returned by Retrieve
Record Locks API. Refer to the APIs for more detailed information.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the database file, and
• *OBJOPR and *READ authority to the database file
The following table describes the columns in the view. The system name is RCD_LOCK. The schema is
QSYS2.
Table 279. RECORD_LOCK_INFO view

Column Name System Column Name Data Type Description

TABLE_SCHEMA TABSCHEMA VARCHAR(128) Name of the schema.

TABLE_NAME TABNAME VARCHAR(128) Name of the table.

TABLE_PARTITION TABPART VARCHAR(128) Name of the table partition or member that contains the locked
record.

SYSTEM_TABLE_SCHEMA SYS_DNAME VARCHAR(10) System name of the schema.

SYSTEM_TABLE_NAME SYS_TNAME VARCHAR(10) System name of the table

SYSTEM_TABLE_MEMBER SYS_MNAME VARCHAR(10) The name of the member that contains the locked record.

RELATIVE_RECORD_NUMBER RRN BIGINT The relative record number (RRN) of the record that is locked.

LOCK_STATE LOCK_STATE VARCHAR(8) The lock condition for the record.

READ The record is locked for read. Another job may


read the same record but cannot lock the record
for update intent. The record cannot be changed
by another job as long as one job holds a read
lock on the record.

UPDATE The record is locked for update intent. Another


job may read the record but may not obtain a read
or update lock on it until the lock is released.

INTERNAL The row is locked internally for read. For a short


time the operating system holds an internal lock
to access the row. Another job may read the same
row and may even have the row locked for update
intent. However, if another job does have the row
locked for update intent, the actual change of
the row will not proceed until the internal lock
is released.

LOCK_STATUS STATUS VARCHAR(9) The status of the lock.

HELD The lock is currently held by the job.

WAITING The job is waiting for the lock.

LOCK_SCOPE LOCK_SCOPE VARCHAR(10) The scope of the lock. Values are:


• JOB
• THREAD
• LOCK SPACE

JOB_NAME JOB_NAME VARCHAR(28) The qualified job name.

Database performance and query optimization 1089


Table 279. RECORD_LOCK_INFO view (continued)

Column Name System Column Name Data Type Description

THREAD_ID THREAD_ID BIGINT The thread that is associated with the lock.

Nullable • If a held lock is job scoped, returns the null value. If a held
lock is thread scoped, contains the identifier for the thread
holding the lock.
• If the scope of the lock is to the lock space and the lock is not
held, contains the identifier of the thread requesting the lock.
• If the lock is requested but not yet available, contains the
identifier of the thread requesting the lock.

LOCK_SPACE_ID LOCKID BINARY(20) When the LOCK_SCOPE column value is LOCK SPACE and the
lock is being waited on by a thread, contains the lock space ID
Nullable value for which the lock is being waited on.
Otherwise, contains the null value.

Example
Review the jobs that are updating the SALES table:

SELECT JOB_NAME, COUNT(*) AS ROWS_UPDATING


FROM QSYS2.RECORD_LOCK_INFO
WHERE SYSTEM_TABLE_NAME = 'SALES' AND
SYSTEM_TABLE_SCHEMA = 'TOYSTORE' AND
LOCK_STATE = 'UPDATE'
GROUP BY JOB_NAME
ORDER BY ROWS_UPDATING DESC

REMOVE_TRACKED_JOB_QUEUE procedure
The REMOVE_TRACKED_JOB_QUEUE procedure removes a job queue from the tracked job queue list.
All information associated with the specified job queue is removed from the job tracking file.
Unless ignore-errors is YES, the tracking file's IASP must be in the caller's namespace or it must
be the name of an IASP that does not exist. The IASP for the tracking file was specified on the
QSYS2.ADD_TRACKED_JOB_QUEUE procedure with the tracking-file-iasp parameter. It is returned in the
TRACKING_FILE_IASP column of the QSYS2.TRACKED_JOB_QUEUES view.
Authorization: The caller must have *JOBCTL special authority.

REMOVE_TRACKED_JOB_QUEUE ( iasp-name ,
IASP_NAME =>

job-queue-library ,
JOB_QUEUE_LIBRARY =>

job-queue
JOB_QUEUE =>

)
, ignore-errors
IGNORE_ERRORS =>

The schema is QSYS2.

iasp-name A character string that contains the name of the ASP where job-queue-library is located.
Can contain the following special value:

*SYSBAS The job queue library is located in the system ASP (ASP 1) or any basic user
ASPs (ASPs 2-32).

1090 IBM i: Performance and Query Optimization


job-queue- A character string that contains the name of the library containing job-queue.
library
job-queue A character string that contains the name of the job queue to be removed from being
tracked.
ignore-errors A character string expression that identifies what to do when an error is encountered
while removing information from the job tracking file.

NO An error is returned, and the job queue is not removed from tracking. This is the
default.
YES A warning is returned.
The job queue will be removed from tracking without removing associated
information from the job tracking file.

Example
• Remove job queue APPLIB/APPJOBQ from the list of tracked job queues.

CALL QSYS2.REMOVE_TRACKED_JOB_QUEUE(IASP_NAME => '*SYSBAS',


JOB_QUEUE_LIBRARY => 'APPLIB',
JOB_QUEUE => 'APPJOBQ');

ROUTING_ENTRY_INFO view
The ROUTING_ENTRY_INFO view returns information about routing entries.
The values returned for the columns in the view are closely related to the values returned by the Display
Routing Entries panel accessed through the DSPSBSD (Display Subsystem Description) CL command and
by the List Subsystem Entries (QWDLSBSE) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the subsystem description, and
• *USE authority to the subsystem description.
The following table describes the columns in the view. The system name is RTG_INFO. The schema is
QSYS2.
Table 280. ROUTING_ENTRY_INFO view

Column Name System Column Name Data Type Description

SUBSYSTEM_DESCRIPTION_LIBRARY SBSD_LIB VARCHAR(10) The name of the library in which the subsystem
description resides.

SUBSYSTEM_DESCRIPTION SBSD VARCHAR(10) The name of the subsystem about which


information is being returned.

SEQUENCE_NUMBER SEQNO INTEGER The sequence number of the routing entry.

PROGRAM_LIBRARY PGM_LIB VARCHAR(10) The name of the library in which the routing entry
program resides.
Nullable
Contains the null value if PROGRAM_NAME is
*RTGDTA.

Database performance and query optimization 1091


Table 280. ROUTING_ENTRY_INFO view (continued)

Column Name System Column Name Data Type Description

PROGRAM_NAME PGM_NAME VARCHAR(10) The name of the program that is started when a
routing step is started through this routing entry.
Can contain the following special value:

*RTGDTA The program name is taken from


the routing data that was supplied
and matched against this entry.
The qualified program name will be
taken from the routing data in this
case, where the program name is
specified in positions 37 through 46
and the library name is taken from
positions 47 through 56.

CLASS_LIBRARY CLASS_LIB VARCHAR(10) The name of the library in which the routing entry
class resides.

CLASS CLASS VARCHAR(10) The name of the class that is used when a routing
step is started through this routing entry.

MAXIMUM_STEPS MAX_STEPS INTEGER The maximum number of routing steps (jobs)


that can be active at the same time through this
Nullable routing entry.
Contains the null value if the routing entry
specifies *NOMAX, indicating that there is no
maximum.

POOL_ID POOL_ID INTEGER The pool identifier of the storage pool in which the
routing entry program is run.

COMPARISON_DATA COMPDATA VARCHAR(80) A value that is compared with the routing data to
determine whether this is the routing entry that is
used for starting a routing step. Can contain the
following special value:

*ANY Any routing data is considered a match.

COMPARISON_START COMP_START INTEGER The starting position for the routing data
comparison. The comparison between the
Nullable compare value and the routing data begins with
this position in the routing data character string,
and the last character position compared must be
less than or equal to the length of the routing data
used in the comparison.
Contains the null value when COMPARISON_DATA
is *ANY.

RESOURCES_AFFINITY_GROUP RAG VARCHAR(3) Specifies whether jobs using this routing entry are
grouped together having affinity to the same set
of processors and memory.

NO The jobs will not be grouped together.


They will be spread across all the
available system resources.

YES The jobs will be grouped together such


that they will have affinity to the same
system resources.

1092 IBM i: Performance and Query Optimization


Table 280. ROUTING_ENTRY_INFO view (continued)

Column Name System Column Name Data Type Description

THREAD_RESOURCES_AFFINITY_ T_RAG VARCHAR(7) Specifies whether secondary threads running in


GROUP jobs that started through this routing entry are
grouped together with the initial thread, or spread
across the system resources.

GROUP Secondary threads will all have


affinity to the same set of
processors and memory as the
initial thread.

NOGROUP Secondary threads will not


necessarily have affinity to the
same set of processors and
memory as the initial thread. They
will be spread across all the
available system resources.

SYSVAL The thread resources affinity group


and level in the QTHDRSCAFN
system value will be used when the
job starts.

THREAD_RESOURCES_AFFINITY_ T_RAL VARCHAR(6) The degree to which the system tries to


LEVEL maintain the affinity between threads and system
Nullable resources.

HIGH A thread will only use the resources


it has affinity to, and will wait until
they become available if necessary.

NORMAL A thread will use any processor


or memory in the system if the
resources it has affinity to are not
readily available.

Contains the null value when


THREAD_RESOURCES_AFFINITY_GROUP is
SYSVAL.

Example
• List all the routing entries defined for the QBATCH subsystem.

SELECT *
FROM QSYS2.ROUTING_ENTRY_INFO
WHERE SUBSYSTEM_DESCRIPTION_LIBRARY = 'QSYS' AND
SUBSYSTEM_DESCRIPTION = 'QBATCH';

SCHEDULED_JOB_INFO view
The SCHEDULED_JOB_INFO view returns information that can also be seen through the Work with Job
Schedule Entries (WRKJOBSCDE) command interface. Each job schedule entry contains the information
to automatically submit a batch job once or at regularly scheduled intervals.
Authorization: No authority is required to access scheduled job rows. Some columns return the null value
if the caller does not have the required authority. The caller must have *JOBCTL special authority or be
the user profile listed in the SCHEDULED_BY column to see the data in all columns.
The following table describes the columns in the view. The system name is SCHED_JOB. The schema is
QSYS2.
Table 281. SCHEDULED_JOB_INFO view

System Column
Column Name Name Data Type Description

SCHEDULED_JOB_ENTRY_NUMBER ENTRYNO INTEGER The number assigned to the job schedule entry when the entry is
added to the job schedule.

Database performance and query optimization 1093


Table 281. SCHEDULED_JOB_INFO view (continued)

System Column
Column Name Name Data Type Description

SCHEDULED_JOB_NAME SCDJOBNAME VARCHAR(10) The name of the job schedule entry.


This is the simple job name portion of the fully qualified job name
used when the job is submitted. It is also used to identify the job
schedule entry through change, hold, release and remove functions.

SCHEDULED_DATE_VALUE SCDDATEV VARCHAR(14) Indicates the date on which the job is scheduled to be submitted.

SCHEDULED_DATE The date in the SCHEDULED_DATE column is


used

SCHEDULED_DAYS The days in the SCHEDULED_DAYS column


are used

*MONTHSTR The first day of the month is used.

*MONTHEND The last day of the month is used.

SCHEDULED_DATE SCDDATE DATE The date on which the job is scheduled to be submitted.

Nullable Contains the null value if the SCHEDULED_DATE_VALUE column is


not SCHEDULED_DATE.

SCHEDULED_TIME SCDTIME TIME The time when the job is scheduled to be submitted on the
scheduled date.

SCHEDULED_DAYS SCDDAYS VARCHAR(34) The days on which the job is submitted if a specific date is not
specified.
Nullable
The value is a comma separated string with any or all of the values:
*MON *TUE *WED *THU *FRI *SAT *SUN. The single value of *ALL
can be returned to represent all seven values.
Contains the null value if SCHEDULED_DATE_VALUE is not
SCHEDULED_DAYS.

FREQUENCY FREQUENCY VARCHAR(8) How often the job is to be submitted.

*ONCE The job is scheduled to be submitted a single time.

*WEEKLY The job is scheduled to be submitted on the same


day or days of each week at the scheduled time.

*MONTHLY The job is scheduled to be submitted on the same


day or days of each month at the scheduled time.

RELATIVE_DAYS_OF_MONTH RELDAYSMON VARCHAR(13) Specifies which occurrence during the month (for the days listed in
the SCHEDULED_DAYS column) the job is scheduled to be run. The
Nullable value is a comma separated string with up to five of the following
values:

1 The job is scheduled for the first occurrence of the day or


days (SCHEDULED_DAYS: *MON and *WED for example)
of the month.

2 The job is scheduled for the second occurrence of the day


or days of the month.

3 The job is scheduled for the third occurrence of the day or


days of the month.

4 The job is scheduled for the fourth occurrence of the day


or days of the month.

5 The job is scheduled for the fifth occurrence of the day or


days of the month.

*LAST The job is scheduled for the last occurrence of the day or
days of the month.

Contains the null value if the FREQUENCY column does not have a
value of MONTHLY or SCHEDULED_DAYS is null.

RECOVERY_ACTION RECOVERY VARCHAR(7) The recovery action taken when the system is powered down or in
the restricted state at the time a job is scheduled to be submitted.

*SBMRLS Submit a job to the job queue as a released job.

*SBMHLD Submit a job to the job queue as a held job.

*NOSBM Do not submit a job to the job queue.

1094 IBM i: Performance and Query Optimization


Table 281. SCHEDULED_JOB_INFO view (continued)

System Column
Column Name Name Data Type Description

NEXT_SUBMISSION_DATE NXTSUBDATE DATE The next date that the job scheduling process is scheduled to submit
this job.
Nullable
Contains the null value if the job is not scheduled to be submitted
again.

STATUS STATUS VARCHAR(9) The status of the job schedule entry.

HELD The entry is held. If an entry has a status of


HELD at the scheduled date and time, a job is not
submitted.

SAVED The entry is defined with a frequency of ONCE


and a save value of *YES at a time later than the
scheduled date and time.

SCHEDULED The entry is waiting until the scheduled date and


time for a job to be submitted.

JOB_QUEUE_NAME JOBQ VARCHAR(10) The job queue to which the job is scheduled to be
submitted. Can contain the special value of *JOBD, meaning
that the job is submitted to the job queue specified in the
job description listed in the JOB_DESCRIPTION_NAME and
JOB_DESCRIPTION_LIBRARY_NAME columns.

JOB_QUEUE_LIBRARY_NAME JOBQLIB VARCHAR(10) The library containing the job queue.

Nullable Contains the null value if JOB_QUEUE_NAME is *JOBD


.

JOB_QUEUE_STATUS JOBQSTATUS VARCHAR(10) The status of the job queue.

Nullable HLD The job queue is held, but not attached to an active
subsystem.

HLD/SBS The job queue is held and attached to an active


subsystem.

LOCKED The status of the job queue could not be determined


because a lock could not be obtained on the job queue.

RLS The job queue is released, but not attached to an active


subsystem.

RLS/SBS The job queue is released and attached to an active


subsystem.

Contains the null value if JOB_QUEUE_NAME is *JOBD, if the job


queue is not found or is damaged, or if the information is not
available.

DATES_OMITTED OMITDATES VARCHAR(219) A comma separated string with up to 20 dates in *ISO format
indicating dates when the job will not be scheduled to run.
Nullable
Contains the null value if no dates were specified to omit or if the
information is not available.

SCHEDULED_BY CREATEDBY VARCHAR(10) The user profile of the job which added the entry to the job schedule.

DESCRIPTION TEXT VARCHAR(50) The descriptive text for the job schedule entry.

Nullable Contains the null value if the job schedule entry has no description.

COMMAND_STRING COMMAND VARCHAR(512) The command that is run in the submitted job.

Nullable Contains the null value if the information is not available.

USER_PROFILE_FOR_SUBMITTED_JOB SBMJOBUSR VARCHAR(10) The user profile to be used when the job is submitted. Can contain
the special value *JOBD to indicate that the user profile from the job
Nullable description is used.
Contains the null value if the information is not available.

JOB_DESCRIPTION_NAME JOBD VARCHAR(10) The job description used when the job is submitted. Can contain
the special value of *USRPRF to indicate that the job description
Nullable specified in the user profile under which the submitted job runs is
used.
Contains the null value if the information is not available.

Database performance and query optimization 1095


Table 281. SCHEDULED_JOB_INFO view (continued)

System Column
Column Name Name Data Type Description

JOB_DESCRIPTION_LIBRARY_NAME JOBDLIB VARCHAR(10) The library containing the job description.

Nullable Contains the null value if JOB_DESCRIPTION_NAME has a value of


*USRPRF or if the information is not available.

MESSAGE_QUEUE_NAME MSGQ VARCHAR(10) The name of the message queue where the messages for this job
schedule entry are sent. Can contain the special value *USRPRF to
Nullable indicate that the message queue specified in the user profile under
which the submitted job runs is used.
Contains the null value is no specific message queue is associated
with this job schedule entry or if the information is not available.

MESSAGE_QUEUE_LIBRARY_NAME MSGQLIB VARCHAR(10) The library containing the message queue.

Nullable Contains the null value if MESSAGE_QUEUE_NAME is null, contains


the special value of *USRPRF, or if the information is not available.

LAST_SUCCESSFUL_SUBMISSION_ SBMTIMSTMP TIMESTAMP(0) The timestamp when a batch job was last successfully submitted for
TIMESTAMP the job schedule entry.
Nullable
Contains the null value if the job schedule entry has not been used
to submit a job.

LAST_SUCCESSFUL_SUBMISSION_JOB LASTSBMJOB VARCHAR(28) The qualified job name used when this scheduled job was last
submitted.
Nullable
Contains the null value if the scheduled job has never been
submitted or if the information is not available.

LAST_ATTEMPTED_SUBMISSION_ ATTSBMTIM TIMESTAMP(0) The timestamp when this scheduled job was last submitted.
TIMESTAMP Nullable Contains the null value if the scheduled job has never been
submitted or if the information is not available.

LAST_ATTEMPTED_SUBMISSION_STATUS SBMJOBSTS VARCHAR(68) The status from when this scheduled job was last submitted. Values
are:
Nullable
• JOB SUCCESSFULLY SUBMITTED
• LAST JOB SUBMISSION FAILED, CHECK THE JOB MESSAGE
QUEUE FOR DETAILS
• JOB NOT SUBMITTED DUE TO HELD STATUS
• JOB SUBMITTED AFTER SCHEDULED TIME AS SPECIFIED BY
RECOVERY ACTION
• JOB NOT SUBMITTED AS SPECIFIED BY RECOVERY ACTION
Contains the null value if the scheduled job has never been
submitted or if the information is not available.

KEEP_ENTRY KEEP VARCHAR(3) Whether the job schedule entry is kept or removed after the job has
been submitted.
Nullable
YES The job schedule entry is kept.

NO The job schedule entry is removed.

Contains the null value when the FREQUENCY column does not
contain *ONCE or if the information is not available.

Example
Review the job scheduled entries which are no longer in effect, either because they were explicitly held or
because they were scheduled to run a single time and the scheduled date and time has passed.

SELECT * FROM QSYS2.SCHEDULED_JOB_INFO WHERE STATUS IN ('HELD', 'SAVED')


ORDER BY SCHEDULED_BY;

SUBSYSTEM_INFO view
The SUBSYSTEM_INFO view returns information about all subsystems.
The values returned for the columns in the view are closely related to the values returned by the WRKSBS
(Work with Subsystems) CL command and by the Retrieve Subsystem Information (QWDRSBSD) API.

1096 IBM i: Performance and Query Optimization


Authorization: The caller must have:
• *EXECUTE authority to the library containing the subsystem description, and
• *USE authority to the subsystem description.
The following table describes the columns in the view. The system name is SBS_INFO. The schema is
QSYS2.
Table 282. SUBSYSTEM_INFO view

Column Name System Column Name Data Type Description

SUBSYSTEM_DESCRIPTION_LIBRARY SBSD_LIB VARCHAR(10) The name of the library in which the subsystem
description resides.

SUBSYSTEM_DESCRIPTION SBSD VARCHAR(10) The name of the subsystem about which


information is being returned.

STATUS STATUS VARCHAR(10) The status of the subsystem.

ACTIVE The subsystem is running.

ENDING An ENDSBS command has been


issued for the subsystem or
an ENDSYS command has been
issued, but the subsystem is still
running.

INACTIVE The subsystem is not running.

RESTRICTED An ENDSBS command for


the controlling subsystem, an
ENDSYS *ALL command, or an
ENDSYS command has placed
the controlling subsystem in a
restricted condition.

STARTING A STRSBS command has been


issued for the subsystem, but it
is still in the process of being
started.

MAXIMUM_ACTIVE_JOBS MAX_ACT INTEGER The maximum number of jobs that can run or use
resources in the subsystem at one time.
Nullable
Contains the null value if the subsystem
description specifies *NOMAX, indicating that
there is no maximum.

CURRENT_ACTIVE_JOBS CUR_ACT INTEGER The number of jobs currently active in the


subsystem. This number includes held jobs but
excludes jobs that are disconnected or suspended
because of a transfer secondary job or a transfer
group job. If STATUS is INACTIVE, returns 0.

SUBSYSTEM_MONITOR_JOB SBSMONJOB VARCHAR(28) The qualified job name for the subsystem monitor
job as identified to the system.
Nullable
Contains the null value if STATUS is INACTIVE.

TEXT_DESCRIPTION TEXT VARCHAR(50) The text description of the subsystem description.

Nullable Contains the null value if there is no text


description.

CONTROLLING_SUBSYSTEM CTL_SBS VARCHAR(3) Whether this subsystem is the controlling


subsystem.

NO This subsystem is not the controlling


subsystem.

YES This subsystem is the controlling


subsystem.

WORKLOAD_GROUP WRK_GROUP VARCHAR(10) The name of the workload group used for jobs
started in this subsystem.
Nullable
Contains the null value if there is no workload
group defined for the subsystem.

SIGNON_DEVICE_FILE_LIBRARY DEVFILELIB VARCHAR(10) The name of the library in which the sign-on
device file resides.

SIGNON_DEVICE_FILE DEVFILE VARCHAR(10) The name of the sign-on device file.

Database performance and query optimization 1097


Table 282. SUBSYSTEM_INFO view (continued)

Column Name System Column Name Data Type Description

SECONDARY_LANGUAGE_LIBRARY LANG_LIB VARCHAR(10) The name of the subsystem's secondary language


library.
Nullable
Contains the null value if there is no secondary
language library defined for the subsystem.

IASP_NAME IASP_NAME VARCHAR(10) The name of the auxiliary storage pool (ASP)
group associated with the subsystem monitor job.
Nullable This is the name of the primary ASP device in
an ASP group or the name of an ASP device
description.
Contains the null value if the subsystem does
not have an auxiliary storage pool (ASP) group
associated with it. Only the libraries in the system
ASP and any basic user ASPs will be in the library
name space for the subsystem monitor job.

Example
• Show information for all active subsystems.

SELECT *
FROM QSYS2.SUBSYSTEM_INFO
WHERE STATUS = 'ACTIVE';

SUBSYSTEM_POOL_INFO view
The SUBSYSTEM_POOL_INFO view returns information about storage pools defined for subsystems.
The values returned for the columns in the view are closely related to the values returned by the WRKSBS
(Work with Subsystems) CL command and by the Retrieve Subsystem Information (QWDRSBSD) API.
Authorization: The caller must have:
• *EXECUTE authority to the library containing the subsystem description, and
• *USE authority to the subsystem description.
The following table describes the columns in the view. The system name is SBS_POOL. The schema is
QSYS2.
Table 283. SUBSYSTEM_POOL_INFO view

Column Name System Column Name Data Type Description

SUBSYSTEM_DESCRIPTION_LIBRARY SBSD_LIB VARCHAR(10) The name of the library in which the subsystem
description resides.

SUBSYSTEM_DESCRIPTION SBSD VARCHAR(10) The name of the subsystem about which pool
information is being returned.

POOL_ID POOL_ID INTEGER The pool ID for the subsystem pool.

1098 IBM i: Performance and Query Optimization


Table 283. SUBSYSTEM_POOL_INFO view (continued)

Column Name System Column Name Data Type Description

POOL_NAME POOL_NAME VARCHAR(10) The name of the subsystem pool.

*BASE The system base pool,


which can be shared
with other subsystems. The
QBASPOOL system value
defines the base pool's
minimum size. The base pool
contains all main storage not
allocated to other pools. The
QBASACTLVL system value
defines its activity level.

*INTERACT The shared pool used for


interactive work.

*NOSTG No storage size or activity


level is assigned to this
storage pool.

*SHRPOOL1- Shared pools.


*SHRPOOL60

*SPOOL The shared pool for spooling


writers.

*USERPOOL The pool is user-defined.

MAXIMUM_ACTIVE_JOBS MAX_JOBS INTEGER If the pool name is *USERPOOL, the maximum


number of jobs that can be active in the pool at
Nullable one time.
Contains the null value if the pool name is not
*USERPOOL.

POOL_SIZE POOL_SIZE DECIMAL(20,2) If the pool name is *USERPOOL, the amount of


storage, in megabytes, that the pool attempts to
Nullable allocate.
Contains the null value if the pool name is not
*USERPOOL.

Example
• List all the system storage pools in the QBATCH subsystem.

SELECT *
FROM QSYS2.SUBSYSTEM_POOL_INFO
WHERE SUBSYSTEM_DESCRIPTION_LIBRARY = 'QSYS' AND
SUBSYSTEM_DESCRIPTION = 'QBATCH' AND
POOL_NAME <> '*USERPOOL';

SYSTEM_ACTIVITY_INFO table function


The SYSTEM_ACTIVITY_INFO table function returns a single row containing statistical information about
CPU usage.
The information returned is similar to the detail provided by the Work with System Activity (WRKSYSACT)
CL command.
Authorization: The caller must have *JOBCTL special authority.

SYSTEM_ACTIVITY_INFO ( )
delay-seconds
DELAY_SECONDS =>

The schema is QSYS2.

delay- An integer value that specifies an interval of time to wait between statistical readings. Detail
seconds gathered from two points in time is used to calculate the table function results.

Database performance and query optimization 1099


integer A delay of integer seconds separates the collection of details. integer must be a
value of 1 or greater. One second is the default.
No response from the table function is returned until at least integer seconds have
elapsed.

The result of the function is a table containing a single row with the format shown in the following table.
All the columns are nullable.
Table 284. SYSTEM_ACTIVITY_INFO table function

Column Name Data Type Description

AVERAGE_CPU_RATE DECIMAL(20,2) The average CPU rate expressed as a percentage


where 100% indicates the processor is running at
its nominal frequency. A value above or below 100%
indicates how much the processor has been slowed
down (throttled) or speeded up (turbo) relative to
the nominal frequency for the processor model. For
instance, a value of 120% indicates the processor is
running 20% faster against its nominal speed.

AVERAGE_CPU_UTILIZATION DECIMAL(20,2) The average CPU utilization for all the active
processors.

MINIMUM_CPU_UTILIZATION DECIMAL(20,2) The CPU utilization of the processor that reported the
minimum amount of CPU utilization.

MAXIMUM_CPU_UTILIZATION DECIMAL(20,2) The CPU utilization of the processor that reported the
maximum amount of CPU utilization.

Example
Return statistical CPU information. Use the default one second interval.

SELECT * FROM TABLE(QSYS2.SYSTEM_ACTIVITY_INFO());

SYSTEM_STATUS table function


The SYSTEM_STATUS table function returns a single row containing details about the current partition.
The information returned is similar to the detail seen from the Work with System Status (WRKSYSSTS) and
the Work with System Activity (WRKSYSACT) commands, and information available in the HMC and with
the Retrieve Partition Information (dlpar_get_info) API.
Authorization: To see non-null values for the columns from PARTITION_NAME through
UNUSED_CPU_TIME_SHARED_POOL, the caller must have *USE authority to the QSYS/QPMLPMGT service
program.
To return values for TEMPORARY_JOB_STRUCTURES_AVAILABLE and
PERMANENT_JOB_STRUCTURES_AVAILABLE, the caller must have:
• *JOBCTL special authority, and
• *USE authority to the QSYS/QWTCTJBS program.

SYSTEM_STATUS (
reset-statistics
RESET_STATISTICS =>

)
, detailed-info
DETAILED_INFO =>

The schema is QSYS2.

1100 IBM i: Performance and Query Optimization


reset- A character or graphic string expression that contains a value of YES or NO.
statistics
If this parameter has a value of YES, statistics are reset such that the time of this query
execution is used as the new baseline. The columns that contain this statistical data have
names that are prefixed with ELAPSED_. Future invocations of SYSTEM_STATUS within this
connection will return statistical detail relative to the new baseline. If this parameter has a
value of NO, statistics are not reset for the invocation. If this parameter is not specified, the
default is NO.

detailed- A character or graphic string expression that indicates the type of information to be
info returned.

ALL All available system information is returned.


BASIC Only the basic system information is returned. Values
for the columns from TOTAL_JOB_TABLE_ENTRIES through the
JOBLOG_PENDING_JOB_TABLE_ENTRIES, and JOBS_SIGNED_ON through
BATCH_PRINT_WAITING are not returned and will always contain the null value.
This is the default.

The result of the function is a table containing multiple rows with the format shown in the following table.
All the columns are nullable.
Table 285. SYSTEM_STATUS table function

Column Name Data Type Description

TOTAL_JOBS_IN_SYSTEM INTEGER The total number of user and system jobs that are
currently in the system. The total includes:
• All jobs on job queues waiting to be processed.
• All jobs currently active (being processed).
• All jobs that have completed running but still have
output on output queues to be produced.

MAXIMUM_JOBS_IN_SYSTEM INTEGER The maximum number of jobs that are allowed on


the system. When the number of jobs reaches this
maximum, you can no longer submit or start more jobs
on the system. The total includes:
• All jobs on job queues waiting to be processed.
• All jobs currently active (being processed).
• All jobs that have completed running but still have
output on output queues to be produced.

ACTIVE_JOBS_IN_SYSTEM INTEGER The number of jobs active in the system (jobs that have
been started, but have not yet ended), including both
user and system jobs.

INTERACTIVE_JOBS_IN_SYSTEM DECIMAL(10,2) The percentage of interactive performance assigned to


this logical partition. This value is a percentage of the
total interactive performance available to the entire
physical system.

JOBS_SIGNED_ON INTEGER The number of jobs currently signed on the system.


System request jobs and group jobs are not included in
this number.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

JOBS_DISCONNECTED INTEGER The number of jobs that have been disconnected due
to either the selection of option 80 (Temporary sign-
off) or the entry of the Disconnect Job (DSCJOB)
command.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

JOBS_SUSPENDED_BY_SYSREQ INTEGER The number of user jobs that have been temporarily
suspended by system request jobs so that another job
may be run.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

Database performance and query optimization 1101


Table 285. SYSTEM_STATUS table function (continued)

Column Name Data Type Description

JOBS_SUSPENDED_BY_GROUP_JOB INTEGER The number of user jobs that have been temporarily
suspended by group jobs so that another job may be
run.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

JOBS_PRINT_WAITING INTEGER The number of sessions that have ended with printer
output files waiting to print.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

BATCH_RUNNING INTEGER The number of batch jobs currently running on the


system.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

BATCH_WAITING_TO_RUN INTEGER The number of batch jobs on the system that are
currently waiting to run, including those that were
submitted to run at a future date and time. Jobs on
the job schedule that have not been submitted are not
included.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

BATCH_ENDING INTEGER The number of batch jobs that are in the process of
ending due to one of the following conditions:
• The job finished processing normally.
• The job ended before its normal completion point
and is being removed from the system.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

BATCH_MESSAGE_WAIT INTEGER The number of batch jobs waiting for a reply to a


message before they can continue to run.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

BATCH_HELD_WHILE_RUNNING INTEGER The number of batch jobs that had started running, but
are now held.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

BATCH_HELD_ON_JOBQ INTEGER The number of batch jobs that were submitted, but
were held before they could begin running.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

BATCH_ON_HELD_JOBQ INTEGER The number of batch jobs on job queues that have
been assigned to a subsystem, but are being held.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

BATCH_ON_UNASSIGNED_JOBQ INTEGER The number of batch jobs on job queues that have not
been assigned to a subsystem.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

BATCH_PRINT_WAITING INTEGER The number of completed batch jobs that produced


printer output that is waiting to print.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

ELAPSED_TIME INTEGER The time that has elapsed, in seconds, between the
measurement start time and the current system time.

ELAPSED_CPU_USED DECIMAL(10,2) The average of the elapsed time during which the
processing units were in use.

1102 IBM i: Performance and Query Optimization


Table 285. SYSTEM_STATUS table function (continued)

Column Name Data Type Description

ELAPSED_CPU_SHARED DECIMAL(10,2) The percentage of the total shared processor pool


capacity used by all partitions using the pool during
the elapsed time.
Returns null if this is a dedicated partition.

ELAPSED_CPU_UNCAPPED_CAPACITY DECIMAL(10,2) The percentage of the uncapped shared processing


capacity for the partition used since the last time
statistics were reset.
Returns null if this partition cannot use more that its
configured processing capacity.

CONFIGURED_CPUS INTEGER Total number of configured CPUs for the partition.

CPU_SHARING_ATTRIBUTE VARCHAR(8) This attribute indicates whether this partition is


sharing processors. If the value indicates the partition
does not share physical processors, then this partition
uses only dedicated processors. If the value indicates
the partition shares physical processors, then this
partition uses physical processors from a shared pool
of physical processors.

CAPPED Partition shares processors. The


partition is limited to using its
configured capacity.

UNCAPPED Partition shares processors. The


partition can use more than its
configured capacity.

Contains the null value if this is a dedicated partition.

CURRENT_CPU_CAPACITY DECIMAL(10,2) The current processing capacity specifies the


processor units that are being used in the partition.
For a partition sharing physical processors, the current
processing capacity represents the share of the
physical processors in the pool it is running. For
a partition using dedicated processors, the current
processing capacity represents the number of virtual
processors that are currently active in the partition.

AVERAGE_CPU_RATE DECIMAL(20,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page
1099.

AVERAGE_CPU_UTILIZATION DECIMAL(20,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page
1099.

MINIMUM_CPU_UTILIZATION DECIMAL(20,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page
1099.

MAXIMUM_CPU_UTILIZATION DECIMAL(20,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page
1099.

SQL_CPU_UTILIZATION DECIMAL(10,2) Always contains the null value.

MAIN_STORAGE_SIZE BIGINT The amount of main storage, in kilobytes, in the


system.

SYSTEM_ASP_STORAGE BIGINT The storage capacity of the system auxiliary storage


pool (ASP number 1) in millions of bytes. This value
represents the amount of space available for storage of
both permanent and temporary objects.

TOTAL_AUXILIARY_STORAGE BIGINT The total auxiliary storage, in millions of bytes, on the


system.

Database performance and query optimization 1103


Table 285. SYSTEM_STATUS table function (continued)

Column Name Data Type Description

SYSTEM_ASP_USED DECIMAL(10,2) The percentage of the system storage pool (ASP


number 1) currently in use.

CURRENT_TEMPORARY_STORAGE INTEGER The current amount of storage, in millions of bytes, in


use for temporary objects.

MAXIMUM_TEMPORARY_STORAGE_USED INTEGER The largest amount of storage, in millions of bytes,


used for temporary objects at any one time since the
last IPL.

PERMANENT_ADDRESS_RATE DECIMAL(6,3) The percentage of the maximum possible addresses


for permanent objects that have been used.

TEMPORARY_ADDRESS_RATE DECIMAL(6,3) The percentage of the maximum possible addresses


for temporary objects that have been used.

TEMPORARY_256MB_SEGMENTS DECIMAL(10,2) The percentage of the maximum possible temporary


256MB segments that have been used.

TEMPORARY_4GB_SEGMENTS DECIMAL(10,2) The percentage of the maximum possible temporary


4GB segments that have been used.

PERMANENT_256MB_SEGMENTS DECIMAL(10,2) The percentage of the maximum possible permanent


256MB segments that have been used.

PERMANENT_4GB_SEGMENTS DECIMAL(10,2) The percentage of the maximum possible permanent


4GB segments that have been used.

TEMPORARY_JOB_STRUCTURES_AVAILABLE INTEGER The number of temporary job structures that currently


exist on the system that are not in use.
Returns the null value if the user does not have *USE
authority on the QSYS/QWTCTJBS program.

PERMANENT_JOB_STRUCTURES_AVAILABLE INTEGER The number of permanent job structures that currently


exist on the system that are not in use.
Returns the null value if the user does not have *USE
authority on the QSYS/QWTCTJBS program.

TOTAL_JOB_TABLE_ENTRIES INTEGER The total number of job table entries. This


includes AVAILABLE_JOB_TABLE_ENTRIES and
IN_USE_JOB_TABLE_ENTRIES.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

AVAILABLE_JOB_TABLE_ENTRIES INTEGER The total number of job table entries that are available.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

IN_USE_JOB_TABLE_ENTRIES INTEGER The total number of job table entries that are
in use. This includes ACTIVE_JOB_TABLE_ENTRIES,
JOBQ_JOB_TABLE_ENTRIES,
OUTQ_JOB_TABLE_ENTRIES, and
JOBLOG_PENDING_JOB_TABLE_ENTRIES.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

ACTIVE_JOB_TABLE_ENTRIES INTEGER The total number of entries that are in use by active
jobs.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

JOBQ_JOB_TABLE_ENTRIES INTEGER The total number of entries that are in use by jobs on a
JOBQ.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

OUTQ_JOB_TABLE_ENTRIES INTEGER The total number of entries that are in use by jobs that
have ended but have spooled output still attached to
the job.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

1104 IBM i: Performance and Query Optimization


Table 285. SYSTEM_STATUS table function (continued)

Column Name Data Type Description

JOBLOG_PENDING_JOB_TABLE_ENTRIES INTEGER The total number of entries that are in use by jobs that
have ended but have a pending job log.
Contains the null value when the DETAILED_INFO
parameter is BASIC.

HOST_NAME VARCHAR(255) Name of the system where this information was


generated. This is the name set by CHGNETA.

PARTITION_ID INTEGER The identifier for the partition in which this view is
being run.

NUMBER_OF_PARTITIONS INTEGER The number of partitions on the physical machine.


This includes partitions that are currently powered on
(running) and partitions that are powered off.

ACTIVE_THREADS_IN_SYSTEM INTEGER The number of initial and secondary threads in the


system (threads that have been started, but have not
yet ended), including both user and system threads.

RESTRICTED_STATE VARCHAR(3) Whether the system is in restricted state.

NO System is not in restricted state.

YES System is in restricted state.

The columns from PARTITION_NAME through UNUSED_CPU_TIME_SHARED_POOL require the user to have *USE authority on the QSYS/QPMLPMGT
service program. Otherwise, they will contain the null value.

PARTITION_NAME VARGRAPHIC(255) CCSID 1200 The name of the partition as it is known to the HMC.

PARTITION_GROUP_ID INTEGER The LPAR group for this partition.

SHARED_PROCESSOR_POOL_ID INTEGER The shared processor pool this partition is a member


of. A shared processor pool is a set of physical
processors on the physical machine that is used to
run a set of shared processor partitions. A value of 0
indicates the default pool.
Contains the null value if DEDICATED_PROCESSORS is
YES.

DEFINED_MEMORY BIGINT The amount of memory (in megabytes) that was


configured for this partition through the HMC.

MINIMUM_MEMORY BIGINT The minimum amount of main storage (in megabytes)


that can be assigned to this partition.

MAXIMUM_MEMORY BIGINT The maximum amount of main storage (in megabytes)


that can be assigned to this partition.

MEMORY_INCREMENT BIGINT The smallest amount of main storage (in megabytes)


that can be added to or removed from this partition's
memory.

DEDICATED_PROCESSORS VARCHAR(3) Whether the partition uses dedicated processors.

NO The partition does not use dedicated


processors.

YES The partition uses dedicated processors.

PHYSICAL_PROCESSORS INTEGER The number of physical processors in this physical


machine that are available for use. This does not
include processors on demand that have not been
turned on.

PHYSICAL_PROCESSORS_SHARED_POOL INTEGER The number of physical processors that are allocated


to the shared processor pool used by this partition.
Contains the null value if DEDICATED_PROCESSORS is
YES.

MAXIMUM_PHYSICAL_PROCESSORS INTEGER The maximum number of physical processors that can


be active in this physical machine without installing
additional processors. This value includes currently
active processors and any standby (on demand)
processors that are present in this physical machine.

Database performance and query optimization 1105


Table 285. SYSTEM_STATUS table function (continued)

Column Name Data Type Description

DEFINED_VIRTUAL_PROCESSORS INTEGER The number of virtual processors configured for this


partition through the HMC.

VIRTUAL_PROCESSORS INTEGER The number of virtual processors currently used by this


partition.

MINIMUM_VIRTUAL_PROCESSORS INTEGER The minimum number of virtual processors that can be


configured for this partition.

MAXIMUM_VIRTUAL_PROCESSORS INTEGER The maximum number of virtual processors that can


be configured for this partition.

DEFINED_PROCESSING_CAPACITY DECIMAL(5,2) The amount of processing capacity that was configured


for this partition through the HMC.

PROCESSING_CAPACITY DECIMAL(5,2) The current (usable) amount of processing capacity


available to the partition (also known as partition's
entitled capacity).

UNALLOCATED_PROCESSING_CAPACITY DECIMAL(5,2) The amount of processing capacity in the partition


group this partition belongs to, which is not allocated
to any partition and is available for allocation.

MINIMUM_REQUIRED_PROCESSING_CAPACITY DECIMAL(5,2) The minimum amount of processing capacity that


the operating system in this partition requires for its
operation.

MAXIMUM_LICENSED_PROCESSING_CAPACITY DECIMAL(5,2) The current limit on processing capacity of this


partition imposed by the operating system software
license for this partition.

MINIMUM_PROCESSING_CAPACITY DECIMAL(5,2) The minimum amount of processing capacity that can


be assigned to this partition.

MAXIMUM_PROCESSING_CAPACITY DECIMAL(5,2) The maximum amount of processing capacity that can


be assigned to this partition.

PROCESSING_CAPACITY_INCREMENT DECIMAL(5,2) The smallest capacity that can be added to or removed


from this partition's processing capacity.

DEFINED_INTERACTIVE_CAPACITY DECIMAL(5,2) The amount of interactive capacity that was configured


for this partition through the HMC. A partition's
interactive capacity is defined as this partition's
portion of total interactive capacity of the physical
machine.

INTERACTIVE_CAPACITY DECIMAL(5,2) This partition's current (usable) portion of the physical


machine interactive capacity.

INTERACTIVE_THRESHOLD DECIMAL(5,2) The maximum interactive CPU utilization which can


be sustained in this partition, without causing a
disproportionate increase in system overhead.

UNALLOCATED_INTERACTIVE_CAPACITY DECIMAL(5,2) The amount of interactive capacity in the partition


group this partition belongs to, which is not allocated
to any partition and is available for allocation.
Interactive capacity is defined as the portion of total
interactive capacity of the physical machine.

MINIMUM_INTERACTIVE_CAPACITY DECIMAL(5,2) The minimum portion of the physical machine's


interactive capacity that can be assigned to this
partition.

MAXIMUM_INTERACTIVE_CAPACITY DECIMAL(5,2) The maximum portion of the physical machine's


interactive capacity that can be assigned to this
partition.

DEFINED_VARIABLE_CAPACITY_WEIGHT INTEGER The weighting factor that was configured for this
partition through the HMC. Variable capacity weight
is used for uncapped partitions when they compete
for unused CPU cycles in the shared pool. Variable
capacity weight can be in the range of 0 - 255. The
larger the weight, the more the chance this partition
will get additional CPU cycles from the shared pool.
Contains the null value if the
DEDICATED_PROCESSORS is YES or if
CPU_SHARING_ATTRIBUTE is CAPPED.

1106 IBM i: Performance and Query Optimization


Table 285. SYSTEM_STATUS table function (continued)

Column Name Data Type Description

VARIABLE_CAPACITY_WEIGHT INTEGER The weighting factor that is used to assign additional


unused CPU cycles (from the shared processor pool)
to the partition. Variable capacity weight is used for
uncapped partitions when they compete for unused
CPU cycles in the shared pool. This factor is in the
range of 0 - 255. The larger the weight, the greater
the chance this partition will get additional CPU cycles
from the pool. A value of 0 effectively caps this
partition at its current (usable) processing capacity.
Contains the null value if the
DEDICATED_PROCESSORS is YES or if
CPU_SHARING_ATTRIBUTE is CAPPED.

UNALLOCATED_VARIABLE_CAPACITY_WEIGHT INTEGER The amount of capacity weight that is available for


allocation to the partition's variable capacity weight.
Contains the null value if the
DEDICATED_PROCESSORS is YES or if
CPU_SHARING_ATTRIBUTE is CAPPED.

HARDWARE_MULTITHREADING VARCHAR(3) Indicates whether hardware multi-threading is


enabled.

NO Hardware multi-threading is not enabled.

YES Hardware multi-threading is enabled.

BOUND_HARDWARE_THREADS VARCHAR(3) Whether hardware threads are bound.

NO Hardware threads are not bound.

YES Hardware threads are bound.

THREADS_PER_PROCESSOR INTEGER The number of hardware threads per processor when


hardware multi-threading is enabled.
Contains the null value if
HARDWARE_MULTITHREADING is NO.

DISPATCH_LATENCY DECIMAL(20,0) The maximum time in nanoseconds between


dispatches of this partition on a physical processor.

DISPATCH_WHEEL_ROTATION_TIME DECIMAL(20,0) The number of nanoseconds in the hypervisor's


scheduling window. Each virtual processor will be
given the opportunity to execute on a physical
processor some time during this period. The amount
of time each virtual processor is able to use a physical
processor is determined by partition processing
capacity.

TOTAL_CPU_TIME DECIMAL(20,0) The number of nanoseconds of CPU time used by this


partition since IPL.

INTERACTIVE_CPU_TIME DECIMAL(20,0) The amount of CPU time, in nanoseconds, used by


interactive processes in this partition since partition
IPL. An interactive process is any process doing 5250
display device I/O.

INTERACTIVE_CPU_TIME_ABOVE_THRESHOLD DECIMAL(20,0) The amount of CPU time, in nanoseconds, used by


interactive processes while exceeding the interactive
threshold. This is a total since IPL.

UNUSED_CPU_TIME_SHARED_POOL DECIMAL(20,0) The number of nanoseconds of CPU time that the


physical processors in a shared processor pool have
been idle since system IPL.
Contains the null value if DEDICATED_PROCESSORS
is YES or if the partition is not authorized to retrieve
shared pool data.

MACHINE_TYPE CHAR(4) The machine type.

MACHINE_MODEL CHAR(4) The machine model.

SERIAL_NUMBER CHAR(8) The machine serial number.

MACHINE_SERIAL_NUMBER CHAR(8) The machine serial number.

Database performance and query optimization 1107


Table 285. SYSTEM_STATUS table function (continued)

Column Name Data Type Description

ATTENTION_LIGHT VARCHAR(3) The status of the system attention light.

OFF The light is off.

ON The light is on.

IPL_MODE VARCHAR(9) The current IPL mode setting.

AUTOMATIC Used for automatic remote IPL,


automatic IPL by date and time, and
automatic IPL after a power failure.

MANUAL An operator uses the control panel to


direct the system for special needs.

NORMAL Requires no operator intervention


during the IPL.

SECURE Prevents use of the control panel to


perform an IPL.

IPL_TYPE CHAR(1) Type of IPL performed.

A Used for special work, such as applying fixes


(PTFs) and diagnostic work.

B Used for routine work and when directed by a PTF


procedure.

C Reserved for system support.

D Used for special work, such as installing and


reloading programs.

JOURNAL_RECOVERY_COUNT INTEGER Specifies the system wide default journal recovery


count. The journal recovery count allows you to choose
between faster runtime processing of changes to
journaled objects and faster IPL or vary on recovery
after an abnormal shutdown. The value specified
influences the frequency with which journaled objects
are forced to auxiliary storage as those objects
are changed. The specified journal recovery count
indicates the approximate number of journaled
changes that would need to be recovered during
journal synchronization for this journal in the event
of an IPL or vary on after an abnormal shutdown.
A smaller value decreases the number of changes
that would need to be recovered from this journal by
increasing the frequency with which changed objects
are forced to disk. A larger value increases the
runtime processing of changes to journaled objects by
decreasing the frequency with which changed objects
are forced to disk. Changing this value may affect
overall system performance as it affects the utilization
of auxiliary storage devices.
This value can be changed with the Change Journal
Attributes (CHGJRNA) CL command.
The system default for this value is 250,000.

JOURNAL_CACHE_WAIT_TIME INTEGER The cache wait time, in seconds, for journal


environments with caching enabled. The cache wait
time is the maximum number of seconds that the
system will wait before writing any lingering journal
entries from main memory to disk.
This value can be changed with the Change Journal
Attributes (CHGJRNA) CL command.
The system default for this value is 30 seconds.

1108 IBM i: Performance and Query Optimization


Table 285. SYSTEM_STATUS table function (continued)

Column Name Data Type Description

ACCESS_PATH_TARGET_ VARCHAR(7) The time, in minutes, targeted for access path


RECOVERY_TIME protection for the system.

1-1440 The number of minutes set for the system


access path recovery time.

*MIN The system access path recovery time is


set to the minimum access path recovery
time for the system, which provides
for the fastest access path recovery.
The eligible access paths for the entire
system are protected.

*NONE No system access path recovery time


is set. No access path protection is
provided by the system unless needed
to meet an ASP specific target access
path recovery time. However, current
access path exposure is monitored and
estimated access path recovery times are
available.

*OFF No access path protection is provided by


the system. The system does not monitor
current exposure and no estimated
access path recovery times are available.

*SYSDFT The system access path recovery time


is set to the system default value of 50
minutes.

Contains the null value if the user does not have


*JOBCTL special authority.

SMAPP_INCLUDE_ACCESS_PATHS VARCHAR(9) Indicates whether the access path recovery time


includes only those access paths which are considered
eligible for protection or includes all access paths.

*ALL The access path recovery time includes


all access paths, both those that are
and those that are not eligible.

*ELIGIBLE The access path recovery time includes


only those access paths which are
considered eligible for protection.

Contains the null value when


ACCESS_PATH_RECOVERY_TIME is *OFF or if the user
does not have *JOBCTL special authority.

ACCESS_PATH_ ESTIMATED_ INTEGER The amount of time, in minutes, that the system will
RECOVERY_TIME take to recover the access paths on the system during
initial program load (IPL) and during the vary on of all
currently available independent storage pools (IASPs).
This value assumes that all access paths that are
protected are recovered at IPL or during vary on of
IASPs.
The estimated system access path recovery time is
influenced by SMAPP_INCLUDE_ACCESS_PATHS.
• If SMAPP_INCLUDE_ACCESS_PATHS is *ELIGIBLE,
this value is the estimated system access path
recovery time of all the eligible access paths that
are not chosen for protection.
• If SMAPP_INCLUDE_ACCESS_PATHS is *ALL, this
value is the estimated system access path recovery
time of all the eligible access paths that are not
chosen for protection plus all the access paths that
are not eligible for protection.
Contains the null value when
ACCESS_PATH_RECOVERY_TIME is *OFF or if the user
does not have *JOBCTL special authority.

Database performance and query optimization 1109


Table 285. SYSTEM_STATUS table function (continued)

Column Name Data Type Description

ACCESS_PATH_ESTIMATED_INELIGIBLE_ INTEGER The total time, in minutes, that it will take to recover
RECOVERY_TIME all access paths which are not eligible for system-
managed access path protection.
Contains the null value when
ACCESS_PATH_RECOVERY_TIME is *OFF or if the user
does not have *JOBCTL special authority.

SMAPP_DISK_STORAGE_USED BIGINT The total amount of auxiliary disk storage, in


megabytes, used by internal objects that are
used exclusively for system-managed access path
protection (SMAPP). This value is the sum of the
auxiliary storage used for access path protection for
each auxiliary storage pool (ASP).
Contains the null value when
ACCESS_PATH_RECOVERY_TIME is *OFF or if the user
does not have *JOBCTL special authority.

Example
Return storage and CPU status for the partition. Specify to reset all the elapsed values to 0.

SELECT * FROM TABLE(QSYS2.SYSTEM_STATUS(RESET_STATISTICS=>'YES')) X;

SYSTEM_STATUS_INFO view
The SYSTEM_STATUS_INFO view returns a single row containing details about the current partition. This
view uses the QSYS2.SYSTEM_STATUS table function with DETAILED_INFO => 'ALL'.
For better performance, use SYSTEM_STATUS_INFO_BASIC except when the additional job table columns
returned by SYSTEM_STATUS_INFO are needed by the query.
The information returned is similar to the detail seen from the Work with System Status (WRKSYSSTS)
and the Work with System Activity (WRKSYSACT) commands, information available in the HMC and with
the Retrieve Partition Information (dlpar_get_info) API, and journal attribute values. It does not reset the
statistical columns; to do this, use the associated table function, “SYSTEM_STATUS table function” on
page 1100.
Authorization: To see non-null values for the columns from PARTITION_NAME through
UNUSED_CPU_TIME_SHARED_POOL, the caller must have *USE authority to the QSYS/QPMLPMGT service
program.
To return values for TEMPORARY_JOB_STRUCTURES_AVAILABLE and
PERMANENT_JOB_STRUCTURES_AVAILABLE, the caller must have:
• *JOBCTL special authority, and
• *USE authority to the QSYS/QWTCTJBS program.
The following table describes the columns in the view. The system name is SYS_STATUS. The schema is
QSYS2.
Table 286. SYSTEM_STATUS_INFO view

Column Name System Column Name Data Type Description

TOTAL_JOBS_IN_SYSTEM TOTAL_JOBS INTEGER The total number of user and system jobs that are currently in
the system. The total includes:
• All jobs on job queues waiting to be processed.
• All jobs currently active (being processed).
• All jobs that have completed running but still have output on
output queues to be produced.

1110 IBM i: Performance and Query Optimization


Table 286. SYSTEM_STATUS_INFO view (continued)

Column Name System Column Name Data Type Description

MAXIMUM_JOBS_IN_SYSTEM MAX_JOBS INTEGER The maximum number of jobs that are allowed on the system.
When the number of jobs reaches this maximum, you can no
longer submit or start more jobs on the system. The total
includes:
• All jobs on job queues waiting to be processed.
• All jobs currently active (being processed).
• All jobs that have completed running but still have output on
output queues to be produced.

ACTIVE_JOBS_IN_SYSTEM ACT_JOBS INTEGER The number of jobs active in the system (jobs that have been
started, but have not yet ended), including both user and system
jobs.

INTERACTIVE_JOBS_IN_SYSTEM INTER_JOBS DECIMAL(5,2) The percentage of interactive performance assigned to this


logical partition. This value is a percentage of the total interactive
performance available to the entire physical system.

JOBS_SIGNED_ON JOBS_ON INTEGER The number of jobs currently signed on the system. System
request jobs and group jobs are not included in this number.

JOBS_DISCONNECTED JOBS_DSC INTEGER The number of jobs that have been disconnected due to either
the selection of option 80 (Temporary sign-off) or the entry of the
Disconnect Job (DSCJOB) command.

JOBS_SUSPENDED_BY_SYSREQ JOBS_SYSRQ INTEGER The number of user jobs that have been temporarily suspended
by system request jobs so that another job may be run.

JOBS_SUSPENDED_BY_GROUP_JOB JOBS_GRP INTEGER The number of user jobs that have been temporarily suspended
by group jobs so that another job may be run.

JOBS_PRINT_WAITING JOBS_PRT INTEGER The number of sessions that have ended with printer output files
waiting to print.

BATCH_RUNNING BATCH_RUN INTEGER The number of batch jobs currently running on the system.

BATCH_WAITING_TO_RUN BATCH_WAIT INTEGER The number of batch jobs on the system that are currently
waiting to run, including those that were submitted to run at a
future date and time. Jobs on the job schedule that have not
been submitted are not included.

BATCH_ENDING BATCH_END INTEGER The number of batch jobs that are in the process of ending due to
one of the following conditions:
• The job finished processing normally.
• The job ended before its normal completion point and is being
removed from the system.

BATCH_MESSAGE_WAIT BATCH_MSGW INTEGER The number of batch jobs waiting for a reply to a message before
they can continue to run.

BATCH_HELD_WHILE_RUNNING BATCH_RHLD INTEGER The number of batch jobs that had started running, but are now
held.

BATCH_HELD_ON_JOBQ BATCH_SHLD INTEGER The number of batch jobs that were submitted, but were held
before they could begin running.

BATCH_ON_HELD_JOBQ BATCH_JHLD INTEGER The number of batch jobs on job queues that have been assigned
to a subsystem, but are being held.

BATCH_ON_UNASSIGNED_JOBQ BATCH_NOS INTEGER The number of batch jobs on job queues that have not been
assigned to a subsystem.

BATCH_PRINT_WAITING BATCH_PRT INTEGER The number of completed batch jobs that produced printer
output that is waiting to print.

ELAPSED_TIME ELAP_TIME INTEGER The time that has elapsed, in seconds, between the
measurement start time and the current system time.

ELAPSED_CPU_USED ELAP_USED DECIMAL(5,2) The average of the elapsed time during which the processing
units were in use.

ELAPSED_CPU_SHARED ELAP_SHARE DECIMAL(5,2) The percentage of the total shared processor pool capacity used
by all partitions using the pool during the elapsed time.
Nullable
Returns null if this is a dedicated partition.

ELAPSED_CPU_UNCAPPED_ ELAP_UNCAP DECIMAL(5,2) The percentage of the uncapped shared processing capacity
CAPACITY for the partition used since the last time statistics were reset.
Nullable Returns null if this partition cannot use more that its configured
processing capacity.

Database performance and query optimization 1111


Table 286. SYSTEM_STATUS_INFO view (continued)

Column Name System Column Name Data Type Description

CONFIGURED_CPUS CONFIGCPUS INTEGER Total number of configured CPUs for the partition.

CPU_SHARING_ATTRIBUTE CPU_SHARE VARCHAR(8) This attribute indicates whether this partition is sharing
processors. If the value indicates the partition does not share
Nullable physical processors, then this partition uses only dedicated
processors. If the value indicates the partition shares physical
processors, then this partition uses physical processors from a
shared pool of physical processors.

CAPPED Partition shares processors. The partition is


limited to using its configured capacity.

UNCAPPED Partition shares processors. The partition can


use more than its configured capacity.

Contains the null value if this is a dedicated partition.

CURRENT_CPU_CAPACITY CPU_CAP DECIMAL(5,2) The current processing capacity specifies the processor units
that are being used in the partition. For a partition sharing
physical processors, the current processing capacity represents
the share of the physical processors in the pool it is running. For
a partition using dedicated processors, the current processing
capacity represents the number of virtual processors that are
currently active in the partition.

AVERAGE_CPU_RATE CPU_RATE DECIMAL(5,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page 1099.

AVERAGE_CPU_UTILIZATION CPU_AVG DECIMAL(5,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page 1099.

MINIMUM_CPU_UTILIZATION CPU_MIN DECIMAL(5,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page 1099.

MAXIMUM_CPU_UTILIZATION CPU_MAX DECIMAL(5,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page 1099.

SQL_CPU_UTILIZATION CPU_SQL DECIMAL(5,2) Always contains the null value.

Nullable

MAIN_STORAGE_SIZE MAIN_STG BIGINT The amount of main storage, in kilobytes, in the system.

SYSTEM_ASP_STORAGE SYS_STG BIGINT The storage capacity of the system auxiliary storage pool (ASP
number 1) in millions of bytes. This value represents the amount
of space available for storage of both permanent and temporary
objects.

TOTAL_AUXILIARY_STORAGE AUX_STG BIGINT The total auxiliary storage, in millions of bytes, on the system.

SYSTEM_ASP_USED SYS_RATE DECIMAL(5,2) The percentage of the system storage pool (ASP number 1)
currently in use.

CURRENT_TEMPORARY_STORAGE TEMP_CUR INTEGER The current amount of storage, in millions of bytes, in use for
temporary objects.

MAXIMUM_TEMPORARY_STORAGE_ TEMP_MAX INTEGER The largest amount of storage, in millions of bytes, used for
USED temporary objects at any one time since the last IPL.

PERMANENT_ADDRESS_RATE PERM_RATE DECIMAL(6,3) The percentage of the maximum possible addresses for
permanent objects that have been used.

TEMPORARY_ADDRESS_RATE TEMP_RATE DECIMAL(6,3) The percentage of the maximum possible addresses for
temporary objects that have been used.

TEMPORARY_256MB_SEGMENTS TEMP_256MB DECIMAL(5,2) The percentage of the maximum possible temporary 256MB
segments that have been used.

TEMPORARY_4GB_SEGMENTS TEMP_4GB DECIMAL(5,2) The percentage of the maximum possible temporary 4GB
segments that have been used.

1112 IBM i: Performance and Query Optimization


Table 286. SYSTEM_STATUS_INFO view (continued)

Column Name System Column Name Data Type Description

PERMANENT_256MB_SEGMENTS PERM_256MB DECIMAL(5,2) The percentage of the maximum possible permanent 256MB
segments that have been used.

PERMANENT_4GB_SEGMENTS PERM_4GB DECIMAL(5,2) The percentage of the maximum possible permanent 4GB
segments that have been used.

TEMPORARY_JOB_STRUCTURES_ TEMP_JS INTEGER The number of temporary job structures that currently exist on
AVAILABLE the system that are not in use.
Nullable
Returns the null value if the user does not have *USE authority on
the QSYS/QWTCTJBS program.

PERMANENT_JOB_STRUCTURES_ PERM_JS INTEGER The number of permanent job structures that currently exist on
AVAILABLE the system that are not in use.
Nullable
Returns the null value if the user does not have *USE authority on
the QSYS/QWTCTJBS program.

TOTAL_JOB_TABLE_ENTRIES TOTAL_JOBT INTEGER The total number of job table entries.


This includes AVAILABLE_JOB_TABLE_ENTRIES and
IN_USE_JOB_TABLE_ENTRIES.

AVAILABLE_JOB_TABLE_ENTRIES AVAIL_JOBT INTEGER The total number of job table entries that are available.

IN_USE_JOB_TABLE_ENTRIES INUSE_JOBT INTEGER The total number of job table entries that are
in use. This includes ACTIVE_JOB_TABLE_ENTRIES,
JOBQ_JOB_TABLE_ENTRIES, OUTQ_JOB_TABLE_ENTRIES, and
JOBLOG_PENDING_JOB_TABLE_ENTRIES.

ACTIVE_JOB_TABLE_ENTRIES ACT_JOBT INTEGER The total number of entries that are in use by active jobs.

JOBQ_JOB_TABLE_ENTRIES JOBQ_JOBT INTEGER The total number of entries that are in use by jobs on a JOBQ.

OUTQ_JOB_TABLE_ENTRIES OUTQ_JOBT INTEGER The total number of entries that are in use by jobs that have
ended but have spooled output still attached to the job.

JOBLOG_PENDING_JOB_TABLE_ENTRIE PEND_JOBT INTEGER The total number of entries that are in use by jobs that have
S ended but have a pending job log.

HOST_NAME HOST_NAME VARCHAR(255) Name of the system where this information was generated. This
is the name set by CHGNETA.

PARTITION_ID PART_ID INTEGER The identifier for the partition in which this view is being run.

NUMBER_OF_PARTITIONS NUM_PART INTEGER The number of partitions on the physical machine. This includes
partitions that are currently powered on (running) and partitions
that are powered off.

ACTIVE_THREADS_IN_SYSTEM ACT_THREAD INTEGER The number of initial and secondary threads in the system
(threads that have been started, but have not yet ended),
including both user and system threads.

RESTRICTED_STATE REST_STATE VARCHAR(3) Whether the system is in restricted state.

NO System is not in restricted state.

YES System is in restricted state.

The columns from PARTITION_NAME through UNUSED_CPU_TIME_SHARED_POOL require the user to have *USE authority on the QSYS/QPMLPMGT
service program. Otherwise, they will contain the null value.

PARTITION_NAME PART_NAME VARGRAPHIC(25 The name of the partition as it is known to the HMC.
5) CCSID 1200

Nullable

PARTITION_GROUP_ID PART_GROUP INTEGER The LPAR group for this partition.

Nullable

SHARED_PROCESSOR_POOL_ID POOL_ID INTEGER The shared processor pool this partition is a member of. A shared
processor pool is a set of physical processors on the physical
Nullable machine that is used to run a set of shared processor partitions.
A value of 0 indicates the default pool.
Contains the null value if DEDICATED_PROCESSORS is YES.

DEFINED_MEMORY DEF_MEM BIGINT The amount of memory (in megabytes) that was configured for
this partition through the HMC.
Nullable

Database performance and query optimization 1113


Table 286. SYSTEM_STATUS_INFO view (continued)

Column Name System Column Name Data Type Description

MINIMUM_MEMORY MIN_MEM BIGINT The minimum amount of main storage (in megabytes) that can be
assigned to this partition.
Nullable

MAXIMUM_MEMORY MAX_MEM BIGINT The maximum amount of main storage (in megabytes) that can
be assigned to this partition.
Nullable

MEMORY_INCREMENT MEM_INCR BIGINT The smallest amount of main storage (in megabytes) that can be
added to or removed from this partition's memory.
Nullable

DEDICATED_PROCESSORS DED_PROC VARCHAR(3) Whether the partition uses dedicated processors.

Nullable NO The partition does not use dedicated processors.

YES The partition uses dedicated processors.

PHYSICAL_PROCESSORS PHY_PROC INTEGER The number of physical processors in this physical machine
that are available for use. This does not include processors on
Nullable demand that have not been turned on.

PHYSICAL_PROCESSORS_SHARED_ PHY_SHARE INTEGER The number of physical processors that are allocated to the
POOL shared processor pool used by this partition.
Nullable
Contains the null value if DEDICATED_PROCESSORS is YES.

MAXIMUM_PHYSICAL_PROCESSORS MAX_PHY INTEGER The maximum number of physical processors that can be
active in this physical machine without installing additional
Nullable processors. This value includes currently active processors and
any standby (on demand) processors that are present in this
physical machine.

DEFINED_VIRTUAL_PROCESSORS DEF_VIRT INTEGER The number of virtual processors configured for this partition
through the HMC.
Nullable

VIRTUAL_PROCESSORS VIRT_PROC INTEGER The number of virtual processors currently used by this partition.

Nullable

MINIMUM_VIRTUAL_PROCESSORS MIN_VIRT INTEGER The minimum number of virtual processors that can be
configured for this partition.
Nullable

MAXIMUM_VIRTUAL_PROCESSORS MAX_VIRT INTEGER The maximum number of virtual processors that can be
configured for this partition.
Nullable

DEFINED_PROCESSING_CAPACITY DEF_CAP DECIMAL(5,2) The amount of processing capacity that was configured for this
partition through the HMC.
Nullable

PROCESSING_CAPACITY CAPACITY DECIMAL(5,2) The current (usable) amount of processing capacity available to
the partition (also known as partition's entitled capacity).
Nullable

UNALLOCATED_PROCESSING_CAPACITY AVAIL_CAP DECIMAL(5,2) The amount of processing capacity in the partition group this
partition belongs to, which is not allocated to any partition and is
Nullable available for allocation.

MINIMUM_REQUIRED_PROCESSING_ MIN_REQCAP DECIMAL(5,2) The minimum amount of processing capacity that the operating
CAPACITY system in this partition requires for its operation.
Nullable

MAXIMUM_LICENSED_PROCESSING_ MAX_LICCAP DECIMAL(5,2) The current limit on processing capacity of this partition imposed
CAPACITY by the operating system software license for this partition.
Nullable

MINIMUM_PROCESSING_CAPACITY MIN_CAP DECIMAL(5,2) The minimum amount of processing capacity that can be
assigned to this partition.
Nullable

MAXIMUM_PROCESSING_CAPACITY MAX_CAP DECIMAL(5,2) The maximum amount of processing capacity that can be
assigned to this partition.
Nullable

PROCESSING_CAPACITY_INCREMENT CAP_INCR DECIMAL(5,2) The smallest capacity that can be added to or removed from this
partition's processing capacity.
Nullable

1114 IBM i: Performance and Query Optimization


Table 286. SYSTEM_STATUS_INFO view (continued)

Column Name System Column Name Data Type Description

DEFINED_INTERACTIVE_CAPACITY DEF_INTCAP DECIMAL(5,2) The amount of interactive capacity that was configured for this
partition through the HMC. A partition's interactive capacity is
Nullable defined as this partition's portion of total interactive capacity of
the physical machine.

INTERACTIVE_CAPACITY INT_CAP DECIMAL(5,2) This partition's current (usable) portion of the physical machine
interactive capacity.
Nullable

INTERACTIVE_THRESHOLD INT_THRESH DECIMAL(5,2) The maximum interactive CPU utilization which can be sustained
in this partition, without causing a disproportionate increase in
Nullable system overhead.

UNALLOCATED_INTERACTIVE_ AVL_INTCAP DECIMAL(5,2) The amount of interactive capacity in the partition group this
CAPACITY partition belongs to, which is not allocated to any partition and
Nullable is available for allocation. Interactive capacity is defined as the
portion of total interactive capacity of the physical machine.

MINIMUM_INTERACTIVE_CAPACITY MIN_INTCAP DECIMAL(5,2) The minimum portion of the physical machine's interactive
capacity that can be assigned to this partition.
Nullable

MAXIMUM_INTERACTIVE_CAPACITY MAX_INTCAP DECIMAL(5,2) The maximum portion of the physical machine's interactive
capacity that can be assigned to this partition.
Nullable

DEFINED_VARIABLE_CAPACITY_ DEF_CAPW INTEGER The weighting factor that was configured for this partition
WEIGHT through the HMC. Variable capacity weight is used for uncapped
Nullable partitions when they compete for unused CPU cycles in the
shared pool. Variable capacity weight can be in the range of 0
- 255. The larger the weight, the more the chance this partition
will get additional CPU cycles from the shared pool.
Contains the null value if DEDICATED_PROCESSORS is YES or if
CPU_SHARING_ATTRIBUTE is CAPPED.

VARIABLE_CAPACITY_WEIGHT VAR_CAPW INTEGER The weighting factor that is used to assign additional unused
CPU cycles (from the shared processor pool) to the partition.
Nullable Variable capacity weight is used for uncapped partitions when
they compete for unused CPU cycles in the shared pool. This
factor is in the range of 0 - 255. The larger the weight, the greater
the chance this partition will get additional CPU cycles from the
pool. A value of 0 effectively caps this partition at its current
(usable) processing capacity.
Contains the null value if DEDICATED_PROCESSORS is YES or if
CPU_SHARING_ATTRIBUTE is CAPPED.

UNALLOCATED_VARIABLE_CAPACITY_ AVAIL_CAPW INTEGER The amount of capacity weight that is available for allocation to
WEIGHT the partition's variable capacity weight.
Nullable
Contains the null value if DEDICATED_PROCESSORS is YES or if
CPU_SHARING_ATTRIBUTE is CAPPED.

HARDWARE_MULTITHREADING HW_MLT_THR VARCHAR(3) Indicates whether hardware multi-threading is enabled.

Nullable NO Hardware multi-threading is not enabled.

YES Hardware multi-threading is enabled.

BOUND_HARDWARE_THREADS HW_BND_THR VARCHAR(3) Whether hardware threads are bound.

Nullable NO Hardware threads are not bound.

YES Hardware threads are bound.

THREADS_PER_PROCESSOR THREADS_PP INTEGER The number of hardware threads per processor when hardware
multi-threading is enabled.
Nullable
Contains the null value if HARDWARE_MULTITHREADING is NO.

DISPATCH_LATENCY LATENCY DECIMAL(20,0) The maximum time in nanoseconds between dispatches of this
partition on a physical processor.
Nullable

DISPATCH_WHEEL_ROTATION_TIME DISPATCH_T DECIMAL(20,0) The number of nanoseconds in the hypervisor's scheduling


window. Each virtual processor will be given the opportunity
Nullable to execute on a physical processor some time during this
period. The amount of time each virtual processor is able to
use a physical processor is determined by partition processing
capacity.

Database performance and query optimization 1115


Table 286. SYSTEM_STATUS_INFO view (continued)

Column Name System Column Name Data Type Description

TOTAL_CPU_TIME CPU_TOTAL DECIMAL(20,0) The number of nanoseconds of CPU time used by this partition
since IPL.
Nullable

INTERACTIVE_CPU_TIME CPU_INTER DECIMAL(20,0) The amount of CPU time, in nanoseconds, used by interactive
processes in this partition since partition IPL. An interactive
Nullable process is any process doing 5250 display device I/O.

INTERACTIVE_CPU_TIME_ABOVE_ CPU_THRESH DECIMAL(20,0) The amount of CPU time, in nanoseconds, used by interactive
THRESHOLD processes while exceeding the interactive threshold. This is a
Nullable total since IPL.

UNUSED_CPU_TIME_SHARED_POOL CPU_UNUSED DECIMAL(20,0) The number of nanoseconds of CPU time that the physical
processors in a shared processor pool have been idle since
Nullable system IPL.
Contains the null value if DEDICATED_PROCESSORS is YES or if
the partition is not authorized to retrieve shared pool data.

MACHINE_TYPE MACH_TYPE CHAR(4) The machine type.

MACHINE_MODEL MACH_MOD CHAR(4) The machine model.

SERIAL_NUMBER SERIAL CHAR(8) The machine serial number.

MACHINE_SERIAL_NUMBER MACH_SER CHAR(8) The machine serial number.

ATTENTION_LIGHT ATTN_LIGHT VARCHAR(3) The status of the system attention light.

OFF The light is off.

ON The light is on.

IPL_MODE IPL_MODE VARCHAR(9) The current IPL mode setting.

AUTOMATIC Used for automatic remote IPL, automatic IPL


by date and time, and automatic IPL after a
power failure.

MANUAL An operator uses the control panel to direct the


system for special needs.

NORMAL Requires no operator intervention during the


IPL.

SECURE Prevents use of the control panel to perform an


IPL.

IPL_TYPE IPL_TYPE CHAR(1) Type of IPL performed.

A Used for special work, such as applying fixes (PTFs) and


diagnostic work.

B Used for routine work and when directed by a PTF


procedure.

C Reserved for system support.

D Used for special work, such as installing and reloading


programs.

1116 IBM i: Performance and Query Optimization


Table 286. SYSTEM_STATUS_INFO view (continued)

Column Name System Column Name Data Type Description

JOURNAL_RECOVERY_COUNT JRNRCYCNT INTEGER Specifies the system wide default journal recovery count. The
journal recovery count allows you to choose between faster
runtime processing of changes to journaled objects and faster
IPL or vary on recovery after an abnormal shutdown. The value
specified influences the frequency with which journaled objects
are forced to auxiliary storage as those objects are changed.
The specified journal recovery count indicates the approximate
number of journaled changes that would need to be recovered
during journal synchronization for this journal in the event of
an IPL or vary on after an abnormal shutdown. A smaller
value decreases the number of changes that would need to
be recovered from this journal by increasing the frequency
with which changed objects are forced to disk. A larger value
increases the runtime processing of changes to journaled objects
by decreasing the frequency with which changed objects are
forced to disk. Changing this value may affect overall system
performance as it affects the utilization of auxiliary storage
devices.
This value can be changed with the Change Journal Attributes
(CHGJRNA) CL command.
The system default for this value is 250,000.

JOURNAL_CACHE_WAIT_TIME CACHEWAIT INTEGER The cache wait time, in seconds, for journal environments with
caching enabled. The cache wait time is the maximum number
of seconds that the system will wait before writing any lingering
journal entries from main memory to disk.
This value can be changed with the Change Journal Attributes
(CHGJRNA) CL command.
The system default for this value is 30 seconds.

ACCESS_PATH_TARGET_ SMAPP VARCHAR(7) The time, in minutes, targeted for access path protection for the
RECOVERY_TIME system.
Nullable
1-1440 The number of minutes set for the system access
path recovery time.

*MIN The system access path recovery time is set to the


minimum access path recovery time for the system,
which provides for the fastest access path recovery.
The eligible access paths for the entire system are
protected.

*NONE No system access path recovery time is set. No


access path protection is provided by the system
unless needed to meet an ASP specific target
access path recovery time. However, current access
path exposure is monitored and estimated access
path recovery times are available.

*OFF No access path protection is provided by the


system. The system does not monitor current
exposure and no estimated access path recovery
times are available.

*SYSDFT The system access path recovery time is set to the


system default value.

Contains the null value if the user does not have *JOBCTL special
authority.

SMAPP_INCLUDE_ACCESS_PATHS SMAPP_AP VARCHAR(9) Indicates whether the access path recovery time should include
only those access paths which are considered eligible for
Nullable protection or include all access paths.

*ALL The access path recovery time includes all access


paths, both those that are and those that are not
eligible.

*ELIGIBLE The access path recovery time includes only


those access paths which are considered eligible
for protection.

Contains the null value when ACCESS_PATH_RECOVERY_TIME is


*OFF or if the user does not have *JOBCTL special authority.

Database performance and query optimization 1117


Table 286. SYSTEM_STATUS_INFO view (continued)

Column Name System Column Name Data Type Description

ACCESS_PATH_ ESTIMATED_ AP_RECOV INTEGER The amount of time, in minutes, that the system will take to
RECOVERY_TIME recover the access paths on the system during initial program
Nullable load (IPL) and during the vary on of all currently available
independent storage pools (IASPs). This value assumes that all
access paths that are protected are recovered at IPL or during
vary on of IASPs.
The estimated system access path recovery time is influenced by
SMAPP_INCLUDE_ACCESS_PATHS.
• If SMAPP_INCLUDE_ACCESS_PATHS is *ELIGIBLE, this value
is the estimated system access path recovery time of all the
eligible access paths that are not chosen for protection.
• If SMAPP_INCLUDE_ACCESS_PATHS is *ALL, this value is the
estimated system access path recovery time of all the eligible
access paths that are not chosen for protection plus all the
access paths that are not eligible for protection.
Contains the null value when ACCESS_PATH_RECOVERY_TIME is
*OFF or if the user does not have *JOBCTL special authority.

ACCESS_PATH_ESTIMATED_INELIGIBLE AP_INELIG INTEGER The total time, in minutes, that it will take to recover all access
_ paths which are not eligible for system-managed access path
Nullable protection.
RECOVERY_TIME
Contains the null value when ACCESS_PATH_RECOVERY_TIME is
*OFF or if the user does not have *JOBCTL special authority.

SMAPP_DISK_STORAGE_USED SMAPP_STG BIGINT The total amount of auxiliary disk storage, in megabytes, used by
internal objects that are used exclusively for system-managed
Nullable access path protection (SMAPP). This value is the sum of
the auxiliary storage used for access path protection for each
auxiliary storage pool (ASP).
Contains the null value when ACCESS_PATH_RECOVERY_TIME is
*OFF or if the user does not have *JOBCTL special authority.

Examples
• Review the state of the job table entries for the partition.

SELECT TOTAL_JOB_TABLE_ENTRIES, AVAILABLE_JOB_TABLE_ENTRIES,


IN_USE_JOB_TABLE_ENTRIES, ACTIVE_JOB_TABLE_ENTRIES,
JOBQ_JOB_TABLE_ENTRIES, OUTQ_JOB_TABLE_ENTRIES,
JOBLOG_PENDING_JOB_TABLE_ENTRIES
FROM QSYS2.SYSTEM_STATUS_INFO;

SYSTEM_STATUS_INFO_BASIC view
The SYSTEM_STATUS_INFO_BASIC view returns a single row containing details about the current
partition. This view uses the QSYS2.SYSTEM_STATUS table function with DETAILED_INFO => 'BASIC'.
This view contains the same information as SYSTEM_STATUS_INFO except it excludes the job table
columns.
The information returned is similar to the detail seen from the Work with System Status (WRKSYSSTS)
and the Work with System Activity (WRKSYSACT) commands, information available in the HMC and with
the Retrieve Partition Information (dlpar_get_info) API, and journal attribute values. It does not reset the
statistical columns; to do this, use the associated table function, “SYSTEM_STATUS table function” on
page 1100.
Authorization: To see non-null values for the columns from PARTITION_NAME through
UNUSED_CPU_TIME_SHARED_POOL, the caller must have *USE authority to the QSYS/QPMLPMGT service
program.
To return values for TEMPORARY_JOB_STRUCTURES_AVAILABLE and
PERMANENT_JOB_STRUCTURES_AVAILABLE, the caller must have:
• *JOBCTL special authority, and
• *USE authority to the QSYS/QWTCTJBS program.

1118 IBM i: Performance and Query Optimization


The following table describes the columns in the view. The system name is SYS_STAT_B. The schema is
QSYS2.
Table 287. SYSTEM_STATUS_INFO _BASIC view

Column Name System Column Name Data Type Description

TOTAL_JOBS_IN_SYSTEM TOTAL_JOBS INTEGER The total number of user and system jobs that are currently in
the system. The total includes:
• All jobs on job queues waiting to be processed.
• All jobs currently active (being processed).
• All jobs that have completed running but still have output on
output queues to be produced.

MAXIMUM_JOBS_IN_SYSTEM MAX_JOBS INTEGER The maximum number of jobs that are allowed on the system.
When the number of jobs reaches this maximum, you can no
longer submit or start more jobs on the system. The total
includes:
• All jobs on job queues waiting to be processed.
• All jobs currently active (being processed).
• All jobs that have completed running but still have output on
output queues to be produced.

ACTIVE_JOBS_IN_SYSTEM ACT_JOBS INTEGER The number of jobs active in the system (jobs that have been
started, but have not yet ended), including both user and system
jobs.

INTERACTIVE_JOBS_IN_SYSTEM INTER_JOBS DECIMAL(5,2) The percentage of interactive performance assigned to this


logical partition. This value is a percentage of the total interactive
performance available to the entire physical system.

ELAPSED_TIME ELAP_TIME INTEGER The time that has elapsed, in seconds, between the
measurement start time and the current system time.

ELAPSED_CPU_USED ELAP_USED DECIMAL(5,2) The average of the elapsed time during which the processing
units were in use.

ELAPSED_CPU_SHARED ELAP_SHARE DECIMAL(5,2) The percentage of the total shared processor pool capacity used
by all partitions using the pool during the elapsed time.
Nullable
Returns null if this is a dedicated partition.

ELAPSED_CPU_UNCAPPED_ ELAP_UNCAP DECIMAL(5,2) The percentage of the uncapped shared processing capacity
CAPACITY for the partition used since the last time statistics were reset.
Nullable Returns null if this partition cannot use more that its configured
processing capacity.

CONFIGURED_CPUS CONFIGCPUS INTEGER Total number of configured CPUs for the partition.

CPU_SHARING_ATTRIBUTE CPU_SHARE VARCHAR(8) This attribute indicates whether this partition is sharing
processors. If the value indicates the partition does not share
Nullable physical processors, then this partition uses only dedicated
processors. If the value indicates the partition shares physical
processors, then this partition uses physical processors from a
shared pool of physical processors.

CAPPED Partition shares processors. The partition is


limited to using its configured capacity.

UNCAPPED Partition shares processors. The partition can


use more than its configured capacity.

Contains the null value if this is a dedicated partition.

CURRENT_CPU_CAPACITY CPU_CAP DECIMAL(5,2) The current processing capacity specifies the processor units
that are being used in the partition. For a partition sharing
physical processors, the current processing capacity represents
the share of the physical processors in the pool it is running. For
a partition using dedicated processors, the current processing
capacity represents the number of virtual processors that are
currently active in the partition.

AVERAGE_CPU_RATE CPU_RATE DECIMAL(5,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page 1099.

Database performance and query optimization 1119


Table 287. SYSTEM_STATUS_INFO _BASIC view (continued)

Column Name System Column Name Data Type Description

AVERAGE_CPU_UTILIZATION CPU_AVG DECIMAL(5,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page 1099.

MINIMUM_CPU_UTILIZATION CPU_MIN DECIMAL(5,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page 1099.

MAXIMUM_CPU_UTILIZATION CPU_MAX DECIMAL(5,2) Always returns 0.


This information has moved to the
QSYS2.SYSTEM_ACTIVITY_INFO table function:
“SYSTEM_ACTIVITY_INFO table function” on page 1099.

SQL_CPU_UTILIZATION CPU_SQL DECIMAL(5,2) Always contains the null value.

Nullable

MAIN_STORAGE_SIZE MAIN_STG BIGINT The amount of main storage, in kilobytes, in the system.

SYSTEM_ASP_STORAGE SYS_STG BIGINT The storage capacity of the system auxiliary storage pool (ASP
number 1) in millions of bytes. This value represents the amount
of space available for storage of both permanent and temporary
objects.

TOTAL_AUXILIARY_STORAGE AUX_STG BIGINT The total auxiliary storage, in millions of bytes, on the system.

SYSTEM_ASP_USED SYS_RATE DECIMAL(5,2) The percentage of the system storage pool (ASP number 1)
currently in use.

CURRENT_TEMPORARY_STORAGE TEMP_CUR INTEGER The current amount of storage, in millions of bytes, in use for
temporary objects.

MAXIMUM_TEMPORARY_STORAGE_ TEMP_MAX INTEGER The largest amount of storage, in millions of bytes, used for
USED temporary objects at any one time since the last IPL.

PERMANENT_ADDRESS_RATE PERM_RATE DECIMAL(6,3) The percentage of the maximum possible addresses for
permanent objects that have been used.

TEMPORARY_ADDRESS_RATE TEMP_RATE DECIMAL(6,3) The percentage of the maximum possible addresses for
temporary objects that have been used.

TEMPORARY_256MB_SEGMENTS TEMP_256MB DECIMAL(5,2) The percentage of the maximum possible temporary 256MB
segments that have been used.

TEMPORARY_4GB_SEGMENTS TEMP_4GB DECIMAL(5,2) The percentage of the maximum possible temporary 4GB
segments that have been used.

PERMANENT_256MB_SEGMENTS PERM_256MB DECIMAL(5,2) The percentage of the maximum possible permanent 256MB
segments that have been used.

PERMANENT_4GB_SEGMENTS PERM_4GB DECIMAL(5,2) The percentage of the maximum possible permanent 4GB
segments that have been used.

TEMPORARY_JOB_STRUCTURES_ TEMP_JS INTEGER The number of temporary job structures that currently exist on
AVAILABLE the system that are not in use.
Nullable
Returns the null value if the user does not have *USE authority on
the QSYS/QWTCTJBS program.

PERMANENT_JOB_STRUCTURES_ PERM_JS INTEGER The number of permanent job structures that currently exist on
AVAILABLE the system that are not in use.
Nullable
Returns the null value if the user does not have *USE authority on
the QSYS/QWTCTJBS program.

HOST_NAME HOST_NAME VARCHAR(255) Name of the system where this information was generated. This
is the name set by CHGNETA.

PARTITION_ID PART_ID INTEGER The identifier for the partition in which this view is being run.

NUMBER_OF_PARTITIONS NUM_PART INTEGER The number of partitions on the physical machine. This includes
partitions that are currently powered on (running) and partitions
that are powered off.

ACTIVE_THREADS_IN_SYSTEM ACT_THREAD INTEGER The number of initial and secondary threads in the system
(threads that have been started, but have not yet ended),
including both user and system threads.

1120 IBM i: Performance and Query Optimization


Table 287. SYSTEM_STATUS_INFO _BASIC view (continued)

Column Name System Column Name Data Type Description

RESTRICTED_STATE REST_STATE VARCHAR(3) Whether the system is in restricted state.

NO System is not in restricted state.

YES System is in restricted state.

The columns from PARTITION_NAME through UNUSED_CPU_TIME_SHARED_POOL require the user to have *USE authority on the QSYS/QPMLPMGT
service program. Otherwise, they will contain the null value.

PARTITION_NAME PART_NAME VARGRAPHIC(25 The name of the partition as it is known to the HMC.
5) CCSID 1200

Nullable

PARTITION_GROUP_ID PART_GROUP INTEGER The LPAR group for this partition.

Nullable

SHARED_PROCESSOR_POOL_ID POOL_ID INTEGER The shared processor pool this partition is a member of. A shared
processor pool is a set of physical processors on the physical
Nullable machine that is used to run a set of shared processor partitions.
A value of 0 indicates the default pool.
Contains the null value if DEDICATED_PROCESSORS is YES.

DEFINED_MEMORY DEF_MEM BIGINT The amount of memory (in megabytes) that was configured for
this partition through the HMC.
Nullable

MINIMUM_MEMORY MIN_MEM BIGINT The minimum amount of main storage (in megabytes) that can be
assigned to this partition.
Nullable

MAXIMUM_MEMORY MAX_MEM BIGINT The maximum amount of main storage (in megabytes) that can
be assigned to this partition.
Nullable

MEMORY_INCREMENT MEM_INCR BIGINT The smallest amount of main storage (in megabytes) that can be
added to or removed from this partition's memory.
Nullable

DEDICATED_PROCESSORS DED_PROC VARCHAR(3) Whether the partition uses dedicated processors.

Nullable NO The partition does not use dedicated processors.

YES The partition uses dedicated processors.

PHYSICAL_PROCESSORS PHY_PROC INTEGER The number of physical processors in this physical machine
that are available for use. This does not include processors on
Nullable demand that have not been turned on.

PHYSICAL_PROCESSORS_SHARED_ PHY_SHARE INTEGER The number of physical processors that are allocated to the
POOL shared processor pool used by this partition.
Nullable
Contains the null value if DEDICATED_PROCESSORS is YES.

MAXIMUM_PHYSICAL_PROCESSORS MAX_PHY INTEGER The maximum number of physical processors that can be
active in this physical machine without installing additional
Nullable processors. This value includes currently active processors and
any standby (on demand) processors that are present in this
physical machine.

DEFINED_VIRTUAL_PROCESSORS DEF_VIRT INTEGER The number of virtual processors configured for this partition
through the HMC.
Nullable

VIRTUAL_PROCESSORS VIRT_PROC INTEGER The number of virtual processors currently used by this partition.

Nullable

MINIMUM_VIRTUAL_PROCESSORS MIN_VIRT INTEGER The minimum number of virtual processors that can be
configured for this partition.
Nullable

MAXIMUM_VIRTUAL_PROCESSORS MAX_VIRT INTEGER The maximum number of virtual processors that can be
configured for this partition.
Nullable

Database performance and query optimization 1121


Table 287. SYSTEM_STATUS_INFO _BASIC view (continued)

Column Name System Column Name Data Type Description

DEFINED_PROCESSING_CAPACITY DEF_CAP DECIMAL(5,2) The amount of processing capacity that was configured for this
partition through the HMC.
Nullable

PROCESSING_CAPACITY CAPACITY DECIMAL(5,2) The current (usable) amount of processing capacity available to
the partition (also known as partition's entitled capacity).
Nullable

UNALLOCATED_PROCESSING_CAPACITY AVAIL_CAP DECIMAL(5,2) The amount of processing capacity in the partition group this
partition belongs to, which is not allocated to any partition and is
Nullable available for allocation.

MINIMUM_REQUIRED_PROCESSING_ MIN_REQCAP DECIMAL(5,2) The minimum amount of processing capacity that the operating
CAPACITY system in this partition requires for its operation.
Nullable

MAXIMUM_LICENSED_PROCESSING_ MAX_LICCAP DECIMAL(5,2) The current limit on processing capacity of this partition imposed
CAPACITY by the operating system software license for this partition.
Nullable

MINIMUM_PROCESSING_CAPACITY MIN_CAP DECIMAL(5,2) The minimum amount of processing capacity that can be
assigned to this partition.
Nullable

MAXIMUM_PROCESSING_CAPACITY MAX_CAP DECIMAL(5,2) The maximum amount of processing capacity that can be
assigned to this partition.
Nullable

PROCESSING_CAPACITY_INCREMENT CAP_INCR DECIMAL(5,2) The smallest capacity that can be added to or removed from this
partition's processing capacity.
Nullable

DEFINED_INTERACTIVE_CAPACITY DEF_INTCAP DECIMAL(5,2) The amount of interactive capacity that was configured for this
partition through the HMC. A partition's interactive capacity is
Nullable defined as this partition's portion of total interactive capacity of
the physical machine.

INTERACTIVE_CAPACITY INT_CAP DECIMAL(5,2) This partition's current (usable) portion of the physical machine
interactive capacity.
Nullable

INTERACTIVE_THRESHOLD INT_THRESH DECIMAL(5,2) The maximum interactive CPU utilization which can be sustained
in this partition, without causing a disproportionate increase in
Nullable system overhead.

UNALLOCATED_INTERACTIVE_ AVL_INTCAP DECIMAL(5,2) The amount of interactive capacity in the partition group this
CAPACITY partition belongs to, which is not allocated to any partition and
Nullable is available for allocation. Interactive capacity is defined as the
portion of total interactive capacity of the physical machine.

MINIMUM_INTERACTIVE_CAPACITY MIN_INTCAP DECIMAL(5,2) The minimum portion of the physical machine's interactive
capacity that can be assigned to this partition.
Nullable

MAXIMUM_INTERACTIVE_CAPACITY MAX_INTCAP DECIMAL(5,2) The maximum portion of the physical machine's interactive
capacity that can be assigned to this partition.
Nullable

DEFINED_VARIABLE_CAPACITY_ DEF_CAPW INTEGER The weighting factor that was configured for this partition
WEIGHT through the HMC. Variable capacity weight is used for uncapped
Nullable partitions when they compete for unused CPU cycles in the
shared pool. Variable capacity weight can be in the range of 0
- 255. The larger the weight, the more the chance this partition
will get additional CPU cycles from the shared pool.
Contains the null value if DEDICATED_PROCESSORS is YES or if
CPU_SHARING_ATTRIBUTE is CAPPED.

VARIABLE_CAPACITY_WEIGHT VAR_CAPW INTEGER The weighting factor that is used to assign additional unused
CPU cycles (from the shared processor pool) to the partition.
Nullable Variable capacity weight is used for uncapped partitions when
they compete for unused CPU cycles in the shared pool. This
factor is in the range of 0 - 255. The larger the weight, the greater
the chance this partition will get additional CPU cycles from the
pool. A value of 0 effectively caps this partition at its current
(usable) processing capacity.
Contains the null value if DEDICATED_PROCESSORS is YES or if
CPU_SHARING_ATTRIBUTE is CAPPED.

1122 IBM i: Performance and Query Optimization


Table 287. SYSTEM_STATUS_INFO _BASIC view (continued)

Column Name System Column Name Data Type Description

UNALLOCATED_VARIABLE_CAPACITY_ AVAIL_CAPW INTEGER The amount of capacity weight that is available for allocation to
WEIGHT the partition's variable capacity weight.
Nullable
Contains the null value if DEDICATED_PROCESSORS is YES or if
CPU_SHARING_ATTRIBUTE is CAPPED.

HARDWARE_MULTITHREADING HW_MLT_THR VARCHAR(3) Indicates whether hardware multi-threading is enabled.

Nullable NO Hardware multi-threading is not enabled.

YES Hardware multi-threading is enabled.

BOUND_HARDWARE_THREADS HW_BND_THR VARCHAR(3) Whether hardware threads are bound.

Nullable NO Hardware threads are not bound.

YES Hardware threads are bound.

THREADS_PER_PROCESSOR THREADS_PP INTEGER The number of hardware threads per processor when hardware
multi-threading is enabled.
Nullable
Contains the null value if HARDWARE_MULTITHREADING is NO.

DISPATCH_LATENCY LATENCY DECIMAL(20,0) The maximum time in nanoseconds between dispatches of this
partition on a physical processor.
Nullable

DISPATCH_WHEEL_ROTATION_TIME DISPATCH_T DECIMAL(20,0) The number of nanoseconds in the hypervisor's scheduling


window. Each virtual processor will be given the opportunity
Nullable to execute on a physical processor some time during this
period. The amount of time each virtual processor is able to
use a physical processor is determined by partition processing
capacity.

TOTAL_CPU_TIME CPU_TOTAL DECIMAL(20,0) The number of nanoseconds of CPU time used by this partition
since IPL.
Nullable

INTERACTIVE_CPU_TIME CPU_INTER DECIMAL(20,0) The amount of CPU time, in nanoseconds, used by interactive
processes in this partition since partition IPL. An interactive
Nullable process is any process doing 5250 display device I/O.

INTERACTIVE_CPU_TIME_ABOVE_ CPU_THRESH DECIMAL(20,0) The amount of CPU time, in nanoseconds, used by interactive
THRESHOLD processes while exceeding the interactive threshold. This is a
Nullable total since IPL.

UNUSED_CPU_TIME_SHARED_POOL CPU_UNUSED DECIMAL(20,0) The number of nanoseconds of CPU time that the physical
processors in a shared processor pool have been idle since
Nullable system IPL.
Contains the null value if DEDICATED_PROCESSORS is YES or if
the partition is not authorized to retrieve shared pool data.

MACHINE_TYPE MACH_TYPE CHAR(4) The machine type.

MACHINE_MODEL MACH_MOD CHAR(4) The machine model.

SERIAL_NUMBER SERIAL CHAR(8) The machine serial number.

MACHINE_SERIAL_NUMBER MACH_SER CHAR(8) The machine serial number.

ATTENTION_LIGHT ATTN_LIGHT VARCHAR(3) The status of the system attention light.

OFF The light is off.

ON The light is on.

IPL_MODE IPL_MODE VARCHAR(9) The current IPL mode setting.

AUTOMATIC Used for automatic remote IPL, automatic IPL


by date and time, and automatic IPL after a
power failure.

MANUAL An operator uses the control panel to direct the


system for special needs.

NORMAL Requires no operator intervention during the


IPL.

SECURE Prevents use of the control panel to perform an


IPL.

Database performance and query optimization 1123


Table 287. SYSTEM_STATUS_INFO _BASIC view (continued)

Column Name System Column Name Data Type Description

IPL_TYPE IPL_TYPE CHAR(1) Type of IPL performed.

A Used for special work, such as applying fixes (PTFs) and


diagnostic work.

B Used for routine work and when directed by a PTF


procedure.

C Reserved for system support.

D Used for special work, such as installing and reloading


programs.

JOURNAL_RECOVERY_COUNT JRNRCYCNT INTEGER Specifies the system wide default journal recovery count. The
journal recovery count allows you to choose between faster
runtime processing of changes to journaled objects and faster
IPL or vary on recovery after an abnormal shutdown. The value
specified influences the frequency with which journaled objects
are forced to auxiliary storage as those objects are changed.
The specified journal recovery count indicates the approximate
number of journaled changes that would need to be recovered
during journal synchronization for this journal in the event of
an IPL or vary on after an abnormal shutdown. A smaller
value decreases the number of changes that would need to
be recovered from this journal by increasing the frequency
with which changed objects are forced to disk. A larger value
increases the runtime processing of changes to journaled objects
by decreasing the frequency with which changed objects are
forced to disk. Changing this value may affect overall system
performance as it affects the utilization of auxiliary storage
devices.
This value can be changed with the Change Journal Attributes
(CHGJRNA) CL command.
The system default for this value is 250,000.

JOURNAL_CACHE_WAIT_TIME CACHEWAIT INTEGER The cache wait time, in seconds, for journal environments with
caching enabled. The cache wait time is the maximum number
of seconds that the system will wait before writing any lingering
journal entries from main memory to disk.
This value can be changed with the Change Journal Attributes
(CHGJRNA) CL command.
The system default for this value is 30 seconds.

Examples
• Review the storage and CPU status for the partition.

SELECT * FROM QSYS2.SYSTEM_STATUS_INFO_BASIC;

• Return job structure information.

SELECT
(SELECT CURRENT_NUMERIC_VALUE FROM QSYS2.SYSTEM_VALUE_INFO
WHERE SYSTEM_VALUE_NAME = 'QTOTJOB') AS INITIAL_PERM_JOB_STRUCTURES,
(SELECT CURRENT_NUMERIC_VALUE FROM QSYS2.SYSTEM_VALUE_INFO
WHERE SYSTEM_VALUE_NAME = 'QADLTOTJ') AS ADDITIONAL_PERM_JOB_STRUCTURES,
PERMANENT_JOB_STRUCTURES_AVAILABLE AS AVAILABLE_PERM_JOB_STRUCTURES,
PERMANENT_JOB_STRUCTURES_AVAILABLE + TOTAL_JOBS_IN_SYSTEM AS TOTAL_PERM_JOB_STRUCTURES,
(SELECT CURRENT_NUMERIC_VALUE FROM QSYS2.SYSTEM_VALUE_INFO
WHERE SYSTEM_VALUE_NAME = 'QACTJOB') AS INITIAL_TEMP_JOB_STRUCTURES,
(SELECT CURRENT_NUMERIC_VALUE FROM QSYS2.SYSTEM_VALUE_INFO
WHERE SYSTEM_VALUE_NAME = 'QADLACTJ') AS ADDITIONAL_TEMP_JOB_STRUCTURES,
TEMPORARY_JOB_STRUCTURES_AVAILABLE AS AVAILABLE_TEMP_JOB_STRUCTURES,
(SELECT BUCKET_CURRENT_SIZE FROM QSYS2.SYSTMPSTG
WHERE GLOBAL_BUCKET_NAME = '*ACTJOB') AS TOTAL_TEMP_STORAGE_USED
FROM QSYS2.SYSTEM_STATUS_INFO_BASIC;

1124 IBM i: Performance and Query Optimization


SYSTEM_VALUE_INFO view
The SYSTEM_VALUE_INFO view contains information about system values.
The values returned for the columns in the view are closely related to the values returned by the Display
System Value (DSPSYSVAL) CL command. The complete list of system values can be found in Retrieve
System Values (QWCRSVAL) API.
Authorization: The caller must have *ALLOBJ or *AUDIT special authority to retrieve the values for
QAUDCTL, QAUDENDACN, QAUDFRCLVL, QAUDLVL, QAUDLVL2, and QCRTOBJAUD. The value of *NOTAVL
or -1 is returned when accessed by an unauthorized user.
The following table describes the columns in the view. The system name is SYSVALINFO. The schema is
QSYS2.
Table 288. SYSTEM_VALUE_INFO view

Column Name System Column Name Data Type Description

SYSTEM_VALUE_NAME SYSVALNAME VARCHAR(10) Name of the system value.

SYSTEM_VALUE SYSVAL VARGRAPHIC(3840) Contains the formatted system value.


CCSID(1200)

CURRENT_NUMERIC_VALUE CURNUMVAL BIGINT Contains the value if the system value is numeric data. Otherwise, contains
the null value.
Nullable

CURRENT_CHARACTER_VALUE CURCHARVAL VARGRAPHIC(3840) Contains the value if the system value is character data. Otherwise,
CCSID(1200) contains the null value.

Nullable

TEXT_DESCRIPTION TEXT VARCHAR(50) Text that describes the system value.

CATEGORY CATEGORY VARCHAR(7) The type of system value.

*ALC Allocation

*DATTIM Date and time

*EDT Editing

*LIBL Library list

*MSG Message and logging

*SEC Security

*STG Storage

*SYSCTL System control

CHANGEABLE CHANGEABLE VARCHAR(3) Whether the system value can be changed with the Change System Value
(CHGSYSVAL) CL command.

NO The system value cannot be changed.

YES The system value can be changed.

SHIPPED_DEFAULT_VALUE DEFAULT VARGRAPHIC(3840) The default value that is shipped for the system value.
CCSID(1200)

Example
Look at the system values related to maximums and their system shipped defaults..

SELECT SYSTEM_VALUE_NAME, SYSTEM_VALUE, SHIPPED_DEFAULT_VALUE FROM


QSYS2.SYSTEM_VALUE_INFO
WHERE SYSTEM_VALUE_NAME LIKE '%MAX%';

returns

SYSTEM_VALUE_NAME SYSTEM_VALUE SHIPPED_DEFAULT_VALUE


QMAXACTLVL *NOMAX *NOMAX
QMAXSIGN 10 3
QPWDMAXLEN 128 8
QMAXSGNACN 3 3
QMAXJOB 163520 163520
QMAXSPLF 9999 9999

Database performance and query optimization 1125


TRACKED_JOB_INFO table function
The TRACKED_JOB_INFO table function returns information about the requested jobs. The information
can be used to resubmit the job. Some information can be provided on the SBMJOB CL command. Other
information can be provided on the CHGJOB CL command.
Authorization: The caller must have *JOBCTL special authority.

TRACKED_JOB_INFO (
node-name-filter
NODE_NAME_FILTER =>

, iasp-name-filter
IASP_NAME_FILTER =>

, job-queue-library-filter
JOB_QUEUE_LIBRARY_FILTER =>

)
, job-queue-filter
JOB_QUEUE_FILTER =>

The schema is QSYS2.

node-name- A string containing a node name in the job tracking files to be included in the result. If
filter this parameter is omitted, information for all nodes is eligible to be returned.
iasp-name- A string containing a job queue independent ASP name in the job tracking files to be
filter included in the result. Can contain the special value *SYSBAS. If this parameter is
omitted, information for all ASPs is eligible to be returned.
job-queue- A string containing a job queue library name in the job tracking files to be included in
library-filter the result. If this parameter is omitted, information for all tracked job queue libraries is
eligible to be returned.
job-queue- A string containing a job queue name in the job tracking files to be included in the
filter result. If this parameter is omitted, information for all tracked job queue queues is
eligible to be returned.

The result of the function is a table containing rows with the format shown in the following table. All the
columns are nullable.
Table 289. TRACKED_JOB_INFO table function

Column Name Data Type Description

NODE_NAME VARCHAR(8) The name of the IBM i partition where the tracked job
queue is located.

QUALIFIED_JOB_NAME VARCHAR(28) The qualified job name.

JOB_NAME VARCHAR(10) The name of the job.

JOB_USER VARCHAR(10) The user profile for the job.

JOB_NUMBER VARCHAR(6) The number of the job.

COMMAND_OR_REQUEST_DATA VARCHAR(20000) The command the job will run or the request data that
is placed as an entry in the job's message queue.
Contains the null value if no command or request data
for the job has been set.

JOB_ENTERED_SYSTEM_TIME TIMESTAMP(0) The timestamp for when the job was placed on the
system.

1126 IBM i: Performance and Query Optimization


Table 289. TRACKED_JOB_INFO table function (continued)

Column Name Data Type Description

JOB_ACTIVE_TIME TIMESTAMP(0) The timestamp for when the job started.


Contains the null value if the job has not started.

JOB_END_TIME TIMESTAMP(0) The timestamp for when the job ended.


Contains the null value if the job has not ended.

JOB_QUEUE_ASP_NAME VARCHAR(10) The ASP device name where the job queue is located.

JOB_QUEUE_LIBRARY VARCHAR(10) The name of the library containing the job queue.

JOB_QUEUE VARCHAR(10) The name of the job queue for the submitted job.

JOB_DESCRIPTION_LIBRARY VARCHAR(10) The name of the library containing the job description.

JOB_DESCRIPTION VARCHAR(10) The name of the job description used for this job.

JOB_END_SEVERITY INTEGER The return code of the job when it ended.


Contains the null value if the job has not ended.

PROCESSING_UNIT_TIME BIGINT The amount of processing unit time used by the job, in
milliseconds.
Contains the null value if the job has not ended.

JOB_QUEUE_PRIORITY INTEGER The scheduling priority of the job compared to other


jobs on the same job queue. The highest priority is 0
and the lowest is 9.

PRINTER_DEVICE_NAME VARCHAR(10) The printer device used for printing output from this
job.

OUTPUT_QUEUE_LIBRARY VARCHAR(10) The name of the library that contains the default
output queue.
Contains the null value if OUTPUT_QUEUE contains a
special value.

OUTPUT_QUEUE VARCHAR(10) The name of the default output queue that is used
for spooled output produced by this job. The default
output queue is only for spooled printer files that
specify *JOB for the output queue. Can contain the
special value *DEV.

OUTPUT_QUEUE_PRIORITY INTEGER The output priority for spooled output files that this job
produces. The highest priority is 0, and the lowest is 9.

JOB_ACCOUNTING_CODE VARCHAR(15) An identifier assigned to the job by the system to


collect resource use information for the job when job
accounting is active.

RUN_PRIORITY INTEGER The priority at which the job or thread competes for the
processing unit relative to other jobs and threads that
are active at the same time. The run priority ranges
from 1 (highest priority) to 99 (lowest priority).
Contains the null value if the run priority for the job has
not been set.

PRINT_TEXT VARCHAR(30) The line of text that is printed at the bottom of each
page of printed output for the job.

ROUTING_DATA VARCHAR(80) The routing

You might also like