Using the SORT and MERGE Statements
9.1 Sorting Data with the SORT Statement
Sorting Concepts
Records are sorted based on the data values in the sort keys. Sort keys identify
the location of a record or the ordering of data. The following example depicts
unsorted employee name and address records used for creating mailing labels:
Smith,
Jones,
Baker,
Thomas,
Morris,
If you sort the addresses in the previous example in ascending order using the
zip code as the sort key, the mailing labels are printed in the order shown in the
following example:
Thomas,
Jones,
Baker,
Smith,
Morris,
Also, records can be sorted on more that one key at a time. If you need an
alphabetical listing of all employees within each state, you can sort on the state
code first (major sort key) and employee name second (minor sort key).
For example, if you sort the file in ascending order by state and last name,
the employee names and addresses appear in the order shown in the following
example:
SORT KEY
(minor)
Baker,
Jones,
Thomas,
Morris,
Smith,
9.1.1 File Organization Considerations for Sorting
You can sort any file regardless of its organization; furthermore, the organization
of the output file can differ from that of the input file. For example, a sort can
have a sequential input file and a relative output file. In this case, the relative
key for the first record returned from the sort is 1; the second record's relative
key is 2; and so forth. However, if an indexed file is described as output in the
GIVING or OUTPUT PROCEDURE phrases, the first sort key associated with
the ASCENDING phrase must specify the same character positions specified by
the RECORD KEY phrase for that file.
Sections 9.1.2, 9.1.3, and 9.1.4 describe the ASCENDING and DESCENDING
KEY phrases, the USING and GIVING phrases, and the INPUT PROCEDURE
and OUTPUT PROCEDURE phrases for sorting.
9–2 Using the SORT and MERGE Statements
Joe
234 Ash St.
Bill
12 Birch St.
Tom
78 Oak St.
Pete
555 Maple St.
Dick
21 Harris St.
Pete
555 Maple St.
Bill
12 Birch St.
Tom
78 Oak St.
Joe
234 Ash St.
Dick
21 Harris St.
Tom
78 Oak St.
Bill
12 Birch St.
Pete
555 Maple St.
Dick
21 Harris St.
Joe
234 Ash St.
New Boston
NH
Gardner
MA
Ayer
MA
Maynard
MA
Acton
ME
Maynard
MA
Gardner
MA
Ayer
MA
New Boston
NH
Acton
ME
SORT KEY
(major)
Ayer
MA
Gardner
MA
Maynard
MA
Acton
ME
New Boston
NH
04356
01430
01510
01234
05670
SORT KEY
01234
01430
01510
04356
05670
01510
01430
01234
05670
04356
Need help?
Do you have a question about the COBOL AAQ2G1FTK and is the answer not in the manual?