COBOL Internal SORT: Keep Input and Output Procedures from Losing or Repeating Records
An internal COBOL `SORT` is often introduced as a convenient way to order a file. In a production batch program, the harder problem is proving that every eligible record was released once, returned once, and written once when input and output procedures are involved.
An internal COBOL SORT is often introduced as a convenient way to order a file. In a production batch program, the harder problem is proving that every eligible record was released once, returned once, and written once when input and output procedures are involved.
This tutorial uses a fictional daily account extract. It shows the control points that make an internal sort reviewable and helps distinguish a sort issue from an input-selection or output-writing issue.
The job of an input and output procedure
A plain SORT can read an input file and write an output file directly. An input procedure lets the COBOL program decide which records enter the sort. An output procedure receives sorted records and applies final processing before writing them. This is useful when an extract has headers, trailers, rejected records, or selection rules.
That flexibility also moves responsibility into the program:
- The input procedure must open and read its input correctly, then
RELEASEeach eligible record. - The sort itself owns the sort work file and the ordering.
- The output procedure must keep calling
RETURNuntil end of sort, then close the target file. - Counters must describe *which* stage they measure. “Input count” and “sorted output count” are not interchangeable.
Do not assume that a successful step return code proves that the output is complete. A program can end normally after selecting zero records, prematurely ending a return loop, or silently routing records away from the expected output.
A compact working pattern
In this generic example, detail records beginning with D are selected. The key is account number in positions 2 through 9. Headers and trailers are counted but never released to the sort. Names and layouts are deliberately illustrative; adapt them to the site’s copybooks and record conventions.
DATA DIVISION.
FILE SECTION.
FD INFILE.
01 IN-REC PIC X(80).
SD SORT-WORK.
01 SORT-REC.
05 SR-ACCOUNT PIC X(8).
05 SR-DATA PIC X(72).
FD OUTFILE.
01 OUT-REC PIC X(80).
WORKING-STORAGE SECTION.
01 WS-END-IN PIC X VALUE 'N'.
01 WS-END-SORT PIC X VALUE 'N'.
01 WS-READ-COUNT PIC 9(7) VALUE ZERO.
01 WS-RELEASE-COUNT PIC 9(7) VALUE ZERO.
01 WS-RETURN-COUNT PIC 9(7) VALUE ZERO.
01 WS-REJECT-COUNT PIC 9(7) VALUE ZERO.
PROCEDURE DIVISION.
SORT SORT-WORK
ON ASCENDING KEY SR-ACCOUNT
INPUT PROCEDURE IS 2000-SELECT-INPUT
OUTPUT PROCEDURE IS 3000-WRITE-SORTED
END-SORT
.
2000-SELECT-INPUT.
OPEN INPUT INFILE
PERFORM UNTIL WS-END-IN = 'Y'
READ INFILE
AT END
MOVE 'Y' TO WS-END-IN
NOT AT END
ADD 1 TO WS-READ-COUNT
IF IN-REC(1:1) = 'D'
MOVE IN-REC(2:8) TO SR-ACCOUNT
MOVE IN-REC(9:72) TO SR-DATA
RELEASE SORT-REC
ADD 1 TO WS-RELEASE-COUNT
ELSE
ADD 1 TO WS-REJECT-COUNT
END-IF
END-READ
END-PERFORM
CLOSE INFILE
.
3000-WRITE-SORTED.
OPEN OUTPUT OUTFILE
PERFORM UNTIL WS-END-SORT = 'Y'
RETURN SORT-WORK INTO SORT-REC
AT END
MOVE 'Y' TO WS-END-SORT
NOT AT END
MOVE 'D' TO OUT-REC(1:1)
MOVE SR-ACCOUNT TO OUT-REC(2:8)
MOVE SR-DATA TO OUT-REC(9:72)
WRITE OUT-REC
ADD 1 TO WS-RETURN-COUNT
END-RETURN
END-PERFORM
CLOSE OUTFILE
.
```
The important rule is not the paragraph number or field positions. It is the one-way flow:
physical input read
-> eligible detail released
-> sort orders released details
-> each returned detail written
A record that is not released cannot appear in the sorted output. A record that is returned but not written is a program defect, not a sort-order defect.
Reconcile the stages, not just the final file
For a normal run of this example, the primary control relationship is:
READ-COUNT = RELEASE-COUNT + REJECT-COUNT
RELEASE-COUNT = RETURN-COUNT
RETURN-COUNT = output detail records written
The first equation checks selection. The second checks that the sort output procedure drained every released record. The third checks the write path. If output headers or trailers are written separately, exclude them from the detail-write count or record a separate count; otherwise the reconciliation becomes misleading.
| Observation | Most likely area to inspect first | Do not conclude yet |
| --- | --- | --- |
| Read count is lower than the file’s expected details | Input DD, file organization, READ loop, prior step output | That SORT dropped records |
| Release count is lower than read count | Selection condition, record type, field layout | That non-details should have been sorted |
| Release count exceeds return count | RETURN loop, end flag, abend messages, sort diagnostics | That a rerun is safe |
| Return count equals release count but target file is short | Output record construction, WRITE, downstream filter | That the sort key is wrong |
| Counts agree but order is unexpected | Key positions, character/numeric representation, ascending/descending rule | That the input was unsorted incorrectly |
Counters should be emitted in an existing, approved job log or reconciliation report. Avoid putting business values or personally identifiable fields into diagnostic messages merely to make count checking easier.
Failure cases that look like sort failures
Resetting an end flag too late. Working-storage end flags should begin in a known state before the sort. If a program can perform more than one sort in a run, reset the appropriate flags and counters deliberately for each run. Reusing WS-END-SORT = 'Y' makes the output procedure return no records, even though the sort may have received them.
Counting before a successful RELEASE. Increment the release counter only after the RELEASE statement. This keeps the counter tied to a completed stage. The same discipline applies to output: increment the write count only after a successful WRITE under local error-handling conventions.
Using the wrong key slice. In fixed records, an off-by-one position can produce a perfectly successful, perfectly wrong sort. Confirm the key against the copybook or record layout, including whether the key is display, packed, binary, or contains leading signs. A displayed numeric-looking key may not sort in business order if it has mixed formats or inconsistent zero padding.
Treating a file trailer as a detail record. Releasing a control trailer can place it in the middle of the sorted output. Conversely, rejecting a genuine detail because the record-type byte moved after an interface change causes a count difference. Validate the layout version before changing the selection test.
Writing headers in the output procedure without a clear rule. An output procedure is called to retrieve sorted records. If a report header is written there, ensure it is written once before the return loop, not once for every returned record. Better still, make the report assembly flow explicit and test it with zero, one, and many eligible records.
What to verify before a rerun
A missing or duplicated outbound extract can cause downstream duplicate processing. Do not rerun an updating job just because the sort output looks wrong. Capture enough evidence to determine the restart boundary first.
- Preserve the job ID, step name, return code, relevant messages, and the exact input and output dataset generations.
- Obtain the program version, compile/link or deployment identifier, and the copybook/layout version used for that run.
- Record the four stage counts: read, rejected, released, and returned/written. State whether headers and trailers are included.
- Check whether the failed or incomplete output was delivered, consumed, cataloged, or retained by a downstream step.
- Compare a small approved sample: source record type, extracted key, and resulting order. Do not copy sensitive business records into tickets or chat tools.
- Confirm the scheduler’s restart guidance and any checkpoint, commit, or output-disposition rules before changing JCL or reusing a dataset.
- Test the corrected logic in an approved non-production environment with empty input, all-rejected input, one record, duplicate keys, and multiple keys.
Local compiler options, sort product behavior, error exits, and record layouts vary. Follow local standards for SORT diagnostics, file-status handling, and reconciliation reporting; do not add a blind rerun, delete an output generation, or alter an interface layout to force counts to agree.
Practical takeaway
An internal COBOL sort is easiest to support when its stages are observable. Count reads, releases, returns, and writes separately; reconcile them with the selection rule; then investigate the first broken relationship. That evidence-based path protects both the file and the decision to rerun.