Sorting with the SORT verb
The SD file
SORT works on an SD (sort description) file in DATA DIVISION. Like every file it gets a SELECT in FILE-CONTROL, and its record layout matches the records being sorted. The sort keys are named in the SORT verb itself:
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT SORT-FILE ASSIGN TO "sort.tmp".
DATA DIVISION.
FILE SECTION.
SD SORT-FILE.
01 SORT-RECORD.
05 SORT-DEPT PIC X(10).
05 SORT-PAY PIC 9(7)V99.
The SORT verb
SORT names the work file, the keys in ascending or descending order, and where records come from and go. Here it sorts by department ascending, then by pay descending:
SORT SORT-FILE
ON ASCENDING KEY SORT-DEPT
ON DESCENDING KEY SORT-PAY
USING UNSORTED-FILE
GIVING SORTED-FILE.
Input and output procedures
INPUT PROCEDURE filters records before the sort, and OUTPUT PROCEDURE processes them after, one at a time with RETURN. Both are optional: USING and GIVING alone cover the common case.
The code on this page was run with GnuCOBOL 3.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev