In COBOL, arrays are useful to store data internally. Here’s the best example how to define key in Array of OCCURS clause.
What is KEY Phrase
- Earlier post I have discussed about Indexed By phrase. In this post I want to show you, how we can define KEY phrase in an array.
- Tip:SEARCH ALL works only for sorted table. That means, you must define both INDEXED BY and KEY IS phrases on a Table, on which you are searching.
KEY in OCCURS
- The KEY phrase in an OCCURS clause states that the table is sorted by the sequence of keys named data-name-3.
- Each of the fields named by data-name-3 must be part of the table—either items subordinate to this data item or possibly the data-name of the table itself.
- The purpose of the KEY clause is to define the table’s ordering when you use the SEARCH statement with the ALL phrase.
Ascending/Descending KEY is data-name-3
- Data-name-3 can be qualified, but it must not be subscripted even though it is a table element, since the reference is really to the entire table.
- Each key must be described as either ASCENDING or DESCENDING. This defines the order, either from lowest to highest (ASCENDING) or highest to lowest (DESCENDING) in which the table is arranged. The order is determined by either numeric comparison for a numeric data-name-3 or non-numeric comparison for other operands. The keys are listed in order of their significance from major to minor.
- The presence of a KEY clause does not mean that the table is necessarily in sorted order, nor does it cause the table to be sorted. It merely states the expected order of the table.
- The SEARCH statement works correctly only if the table is in the order specified by the keys.
Here is an example of a table defined with two keys:
01 MAIL-INFO. 03 MAIL-LIST OCCURS 1000 TIMES ASCENDING KEY IS STATE, CITY. 05 NAME PIC X(20). 05 ADDRESS PIC X(20) OCCURS 3 TIMES. 05 CITY PIC X(20). 05 STATE PIC XX. 05 ZIP PIC 9(5).
**Important interview question:-
How sorting occurs
- This example shows a table (MAIL-LIST) whose elements are (expected to be) in order by STATE (from lowest to highest).
- Elements of the table with the same STATE will be in order by CITY (from lowest to highest).
- Indexed By and KEY is – Both are different phrases in the context of OCCURS.
- The phrase INDEXED BY, we use to retrieve a record dynamically. The KEY IS, a phrase you can use to sort an array.
Explained how to used Key phrase in COBOL internal table. Syntax is given to understand quickly and real interview questions added.