COBOL sort operations let you put file records in order by one or more key fields. The SORT verb reads an input file, sorts the records (ascending or descending), and writes them to an output file. The MERGE verb combines two or more already-sorted files into one sorted file. Both use a special sort work file (SD) that the run time manages for you. For input/output procedures and RELEASE/RETURN, see Sorting operations.
| File | Role |
|---|---|
| Input file | Supplies records to be sorted (USING) |
| Sort work file (SD) | Temporary storage used by SORT; you do not open it |
| Output file | Receives sorted records (GIVING) |
You define the sort work file with SD (Sort Description) in the File Section. Its record layout must match the records you are sorting. You never OPEN, READ, WRITE, or CLOSE the work file; the SORT statement does that internally.
The simplest form uses USING to name the input file and GIVING to name the output file. You specify one or more keys with ON ASCENDING KEY or ON DESCENDING KEY. The key fields must be part of the sort record.
1234567891011121314151617181920212223FILE SECTION. FD INPUT-FILE. 01 INPUT-REC. 05 IN-KEY PIC X(10). 05 IN-DATA PIC X(70). SD SORT-WORK. 01 SORT-REC. 05 SR-KEY PIC X(10). 05 SR-DATA PIC X(70). FD OUTPUT-FILE. 01 OUTPUT-REC. 05 OUT-KEY PIC X(10). 05 OUT-DATA PIC X(70). PROCEDURE DIVISION. SORT SORT-WORK ON ASCENDING KEY SR-KEY USING INPUT-FILE GIVING OUTPUT-FILE END-SORT STOP RUN.
SORT-WORK is the sort work file (SD). SR-KEY is the sort key. The run time reads from INPUT-FILE, sorts by SR-KEY, and writes to OUTPUT-FILE. Input and output records must be the same length/structure as the sort record (or at least compatible for the compiler).
You can sort by several keys. The first key is the primary key; later keys break ties. For example, sort by department (ascending), then by name (ascending), then by amount (descending).
1234567SORT SORT-WORK ON ASCENDING KEY SR-DEPT ON ASCENDING KEY SR-NAME ON DESCENDING KEY SR-AMT USING INPUT-FILE GIVING OUTPUT-FILE END-SORT.
MERGE is used when you have two or more files that are already sorted by the same key. It reads from all inputs, compares keys, and writes the next smallest (or largest) record to the output. The input files must be sorted; MERGE does not sort them, it only merges.
12345MERGE SORT-WORK ON ASCENDING KEY SR-KEY USING INPUT-FILE-1, INPUT-FILE-2 GIVING OUTPUT-FILE END-MERGE.
SORT is like sorting cards: you have a pile (input), you use a temporary table (work file) to arrange them by number or name, then you put the sorted pile into a new box (output). MERGE is when you already have two sorted piles and you combine them into one sorted pile by always taking the smallest (or largest) card from the top of either pile.
1. Which clause names the file that receives the sorted records?
2. When do you use MERGE instead of SORT?