COBOL Module 7 – Sequential files and the classic batch patterns
SORT and MERGE: input and output procedures
Sort COBOL files on several keys with SORT, filter and summarise records in input and output procedures, merge sorted files and choose a collating order.
What you will learn
- Sort files with SORT ... USING and GIVING on several ascending and descending keys
- Filter and reshape records with INPUT and OUTPUT PROCEDUREs using RELEASE and RETURN
- Merge pre-sorted files and check SORT-RETURN
- Predict how a collating sequence changes the sort order
Before you start
What you’ll learn · Before you start
What you will learn
- Sort files with SORT ... USING and GIVING on several ascending and descending keys
- Filter and reshape records with INPUT and OUTPUT PROCEDUREs using RELEASE and RETURN
- Merge pre-sorted files and check SORT-RETURN
- Predict how a collating sequence changes the sort order
Before you start
On this page
Eight transactions arrive in the order the branches keyed them, and the control-break report of this module needs them by branch, then account, with the largest amount first. SORT puts a whole file in that order with one statement.
Its procedures let the program choose what goes in and use what comes out, MERGE joins files that are already sorted, and the character set decides what “in order” means.
SORT with USING and GIVING orders a whole file by its keys
sortkeys.cob describes the records to sort in an SD entry: The sort description in the FILE SECTION: like an FD, but for the work file of a SORT or MERGE, with the record that names the key fields. The program never opens it., the sort description, and names its sort key: A field of the sort record named in the KEY phrase of SORT or MERGE, ASCENDING or DESCENDING. The leftmost key is the major key, and each later key decides only between records the earlier keys left equal. in the SORT statement. IBM’s reference gives the rule for several keys: “The leftmost data-name is the major key, the next data-name is the next most significant key, and so forth.” Here the branch is the major key, then the account, both ascending, and then the amount, descending. TX-SEQ, the last field, numbers the records in the order they arrived:
BR02AC0004C000001250001
BR01AC0002D000012500002
BR01AC0001C000250000003
BR02AC0004D000030000004
BR01AC0002D000012500005
BR03AC0006D000000999006
BR01AC0001D000004999007
BR03AC0007D000150000008 IDENTIFICATION DIVISION.
PROGRAM-ID. SORTKEYS.
* Sorts the day's transactions by branch and account, largest
* amount first, keeping records with equal keys in the order
* they arrived. TX-SEQ is the arrival number of each record.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT TXN-IN ASSIGN TO "TXNIN"
ORGANIZATION IS LINE SEQUENTIAL.
SELECT TXN-OUT ASSIGN TO "TXNOUT"
ORGANIZATION IS LINE SEQUENTIAL.
SELECT SORT-WORK ASSIGN TO "SORTWORK".
DATA DIVISION.
FILE SECTION.
FD TXN-IN.
01 IN-REC PIC X(23).
FD TXN-OUT.
01 OUT-REC PIC X(23).
SD SORT-WORK.
01 SORT-REC.
05 SR-BRANCH PIC X(4).
05 SR-ACCT PIC X(6).
05 SR-TYPE PIC X.
05 SR-AMOUNT PIC 9(7)V99.
05 SR-SEQ PIC 9(3).
WORKING-STORAGE SECTION.
01 SHOW-RETURN PIC 99.
PROCEDURE DIVISION.
SORT SORT-WORK
ON ASCENDING KEY SR-BRANCH SR-ACCT
ON DESCENDING KEY SR-AMOUNT
WITH DUPLICATES IN ORDER
USING TXN-IN
GIVING TXN-OUT
MOVE SORT-RETURN TO SHOW-RETURN
DISPLAY "SORT-RETURN " SHOW-RETURN
STOP RUN. from session import files, run
# Eight transactions in the order they arrived, sorted by branch and account with the largest amount first.
files("sortkeys.cob", "arrivals.txt")
run("""
cobc -x sortkeys.cob
DD_TXNIN=arrivals.txt ./sortkeys && cat TXNOUT
""") Output
$ cobc -x sortkeys.cob $ DD_TXNIN=arrivals.txt ./sortkeys && cat TXNOUT SORT-RETURN 00 BR01AC0001C000250000003 BR01AC0001D000004999007 BR01AC0002D000012500002 BR01AC0002D000012500005 BR02AC0004D000030000004 BR02AC0004C000001250001 BR03AC0006D000000999006 BR03AC0007D000150000008
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 sortkeys_session.py
USING names the input file and GIVING the output file, and the sort opens, reads, writes and closes both itself, which is why IBM’s reference says they “must not be open” when the SORT starts. SORT-RETURN, which IBM documents as “0 (successful) or 16 (unsuccessful)”, printed 00. Within BR01 AC0001, the 2,500.00 credit came before the 49.99 debit because the amount is descending. BR01 AC0002 had two records with the same three keys, 125.00 each, and they kept their arrival order, 002 before 005. That is what WITH DUPLICATES IN ORDER promises; without it, IBM’s reference says, “the order of these records is undefined”. Step through the order the keys produced:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- The input. USING opens arrivals.txt and reads its eight records in arrival order. The first one, 001, is from BR02 and the second, 002, from BR01.
- The major key. The branch decides first, so all four BR01 records come before the two of BR02 and the two of BR03, whatever their accounts and amounts.
- The account. Within BR01 the account decides next, so the two AC0001 records come before the two AC0002 records.
- The amount, largest first. Within BR01 AC0001 the descending amount puts the 2,500.00 credit, 003, before the 49.99 debit, 007. Within BR02 AC0004, 300.00 comes before 12.50.
- Equal keys. Records 002 and 005 are both BR01, AC0002 and 125.00. WITH DUPLICATES IN ORDER keeps them as they arrived, 002 first.
- The output. GIVING opens TXNOUT, writes the eight records in that order and closes it, and SORT-RETURN holds 0.
Keys in the wrong order
Wrong: ON ASCENDING KEY SR-ACCT SR-BRANCH, which sorts by account first and scatters each branch through the file. Right: the major key first, SR-BRANCH then SR-ACCT, in the order the report that reads the file compares them.
Checkpoint
Check: SORT keys, USING and GIVING
Procedures and MERGE replace either end of the sort
Either end of a SORT can be the program’s own code instead of a file. An INPUT PROCEDURE: Paragraphs named in a SORT statement in place of USING. They read the input themselves and pass each record they choose to the sort with a RELEASE statement. reads the input itself and hands only the records it chooses to the sort, each with a RELEASE statement. An OUTPUT PROCEDURE: Paragraphs named in a SORT or MERGE statement in place of GIVING. They receive the sorted records one at a time with a RETURN statement and use them as the program needs. receives the sorted records one at a time with RETURN, instead of GIVING writing them to a file.
MERGE combines two or more files that are each already sorted on the same keys into one file in that order. A MERGE reads its inputs through USING and writes through GIVING or an OUTPUT PROCEDURE, and it has no INPUT PROCEDURE, since its inputs are files that are already in order. A collating sequence: The order in which a program or a sort ranks characters when it compares them. ASCII puts digits before letters and EBCDIC puts letters before digits; COLLATING SEQUENCE names the one a SORT or MERGE uses., named by COLLATING SEQUENCE in the SORT or MERGE statement, decides how letters and digits are ordered against each other: ASCII ranks digits before letters, and EBCDIC, the order of z/OS, ranks letters before digits.
| The sort’s input | The sort’s output | Use it to |
|---|---|---|
| USING a file | GIVING a file | put a whole file in order |
| an INPUT PROCEDURE with RELEASE | GIVING a file | sort only the records you choose |
| USING a file | an OUTPUT PROCEDURE with RETURN | use the sorted records at once, without a sorted file |
| MERGE: USING two or more sorted files | GIVING or an OUTPUT PROCEDURE | join files that are already in order |
On z/OS the work is done by the system’s sort product: IBM’s Programming Guide says that with Enterprise COBOL it “must be DFSORT or an equivalent”.
Key idea
SORT orders a file by its keys, major key first; a procedure at either end lets the program choose what goes in and use what comes out, and MERGE joins files that are each already sorted on the same keys.
Checkpoint
Check: Procedures and MERGE at the ends of a sort
Practise: keys, ends and order
These questions use the eight transactions and their sorted order, and every answer can be checked against the run.
Practice that adapts to you
Practise this lesson
6 questions about 4 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
INPUT and OUTPUT PROCEDUREs in depth: RELEASE, RETURN and a sort stopped with SORT-RETURN Pro: opens with a Pro, Premium or Ultimate pass
A procedure turns a sort into part of the program’s logic. This part runs an input procedure that keeps four of eight records, an output procedure that totals each branch while the sorted records come back, and a damaged record that stops a sort.
In this part:
- An input procedure that keeps four records, and an output procedure that totals each branch
- A damaged record that stops the sort, and a return code the job can see
4 runnable examples (COB, Python) · about 4 minutes
Opening this part with your pass…
This part opens with any MySmartCoPilot pass.
- Pro pass · 1 week₹79$2.99
- 30 days₹179$5.99
- 1 year₹1,699$45
One payment; a pass never renews. The price shown is the total you pay: no fees or charges are added at checkout.
Passes can’t be bought right now, so this part can’t be opened at the moment. The free part above stands on its own. If you have a pass, enter your licence key.
It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).
MERGE and collating order, run and compared, with a portability trap Pro: opens with a Pro, Premium or Ultimate pass
MERGE and COLLATING SEQUENCE are where the same program behaves differently from one platform to another. This part merges two sorted files, gives MERGE a file that is not sorted, and sorts the same six codes in ASCII and in EBCDIC order.
In this part:
- Two sorted files merged, and what GnuCOBOL does with one that is not sorted
- ASCII against EBCDIC: the same six codes in two orders
5 runnable examples (COB, Python, Text) · about 4 minutes
Opening this part with your pass…Pro part. It opens with the same pass as the part above.
Interview questions
First a warm-up with its answer, then three questions about sorts that changed a job’s results:
-
Fresher to mid · Warm-up
What does WITH DUPLICATES IN ORDER do in a COBOL SORT, and when does it matter?
It decides the order of records whose keys are all equal: with the phrase, they come out in the order they went in, so the sort is stable; without it, IBM's reference calls their order undefined. It matters whenever the order of equal-key records carries meaning, for example several transactions for one account that must be applied in the order they happened, or a report that lists them by arrival. In the lesson, two debits of BR01 AC0002 for 125.00, equal on branch, account and amount, kept their arrival order, 002 before 005. When the order matters, make it explicit: keep the phrase, or add a sequence number as the last key.
-
Mid to senior
After the nightly sort step moved to a different sort product, the update that follows it began rejecting some withdrawals as below zero, although the customers had deposited the money first. The sort's only key is the account. What happened, and how do you fix it so that it cannot happen again?
-
Mid to senior
A file sorted on z/OS by product code is copied to a Linux server, converted to ASCII and read by a GnuCOBOL control-break program with a sequence check. On its first night the program stops with records out of order. The codes mix letters and digits. Explain what happened and give two fixes.
-
Senior to staff
A monthly report lists the debits of 10,000.00 or more by branch, from a file of 40 million transactions of which about 2 % qualify. A colleague sorts the whole file and filters afterwards. How would you design the sort step, and what do you expect it to change?
Organisations named on this page
MySmartCoPilot is independent of IBM and of the GnuCOBOL project. The SORT, MERGE, RELEASE and RETURN rules quoted come from IBM’s documentation, the EBCDIC ordering from IBM’s Db2 manual, and every sort and merge shown ran on GnuCOBOL 3.2.
Flashcards · 7 cards
Recall it, then check
Say the answer to yourself before you look: recalling it is what makes it stick.
-
In a SORT with several keys, which key decides first?
The leftmost one, the major key; each key after it orders records whose earlier keys are equal, and each may be ascending or descending.
-
What is an SD entry?
The sort description: it describes the records a SORT works on, as an FD describes the records of a file.
-
Why must the USING and GIVING files be closed when a SORT starts?
The sort opens, reads, writes and closes them itself. SORT-RETURN then says how it went: 0 for success, 16 for failure.
-
What does WITH DUPLICATES IN ORDER promise?
Records with equal keys keep the order in which they arrived. Without the phrase, IBM calls their order undefined.
-
What do an INPUT PROCEDURE and an OUTPUT PROCEDURE do?
An INPUT PROCEDURE reads the input itself and passes the records it chooses to the sort with RELEASE. An OUTPUT PROCEDURE takes the sorted records back one at a time with RETURN instead of a GIVING file.
-
How does MERGE differ from SORT?
MERGE joins two or more files that are each already sorted on the same keys. It reads them through USING and has no INPUT PROCEDURE.
-
Why can the same SORT give another order on z/OS than on a laptop?
The collating sequence differs: ASCII ranks digits before letters, while EBCDIC, the order of z/OS, ranks letters before digits. COLLATING SEQUENCE in the statement names the one to use.
Key takeaways
- SORT with USING and GIVING orders a whole file by its keys, the major key first, each ascending or descending, and SORT-RETURN says 0 when it worked.
- WITH DUPLICATES IN ORDER keeps records with equal keys in their input order, as 002 and 005 stayed; without it their order is undefined.
- An INPUT PROCEDURE chooses the records that are sorted, an OUTPUT PROCEDURE uses the sorted records at once, and MERGE joins files that are each already sorted on the same keys.
Terms in this lesson
- collating sequence
- The order in which a program or a sort ranks characters when it compares them. ASCII puts digits before letters and EBCDIC puts letters before digits; COLLATING SEQUENCE names the one a SORT or MERGE uses.
- INPUT PROCEDURE
- Paragraphs named in a SORT statement in place of USING. They read the input themselves and pass each record they choose to the sort with a RELEASE statement.
- OUTPUT PROCEDURE
- Paragraphs named in a SORT or MERGE statement in place of GIVING. They receive the sorted records one at a time with a RETURN statement and use them as the program needs.
- SD entry
- The sort description in the FILE SECTION: like an FD, but for the work file of a SORT or MERGE, with the record that names the key fields. The program never opens it.
- sort key
- A field of the sort record named in the KEY phrase of SORT or MERGE, ASCENDING or DESCENDING. The leftmost key is the major key, and each later key decides only between records the earlier keys left equal.
References
- Enterprise COBOL for z/OS 6.5: SORT statement (IBM)
- Enterprise COBOL for z/OS 6.5: MERGE statement (IBM)
- Enterprise COBOL for z/OS 6.5: RELEASE statement (IBM)
- Enterprise COBOL for z/OS 6.5: RETURN statement (IBM)
- Enterprise COBOL for z/OS 6.5: SORT-RETURN (IBM)
- Enterprise COBOL for z/OS 6.5 Programming Guide: Sorting and merging files (IBM)
- Enterprise COBOL for z/OS 6.5: ALPHABET clause (IBM)
- z/OS 3.2: DFSORT (IBM)
- Db2 13 for z/OS: String comparisons (IBM)
- GnuCOBOL 3.2 Programmer's Guide (2.1.10 Sorting and Merging Data, 7.8.29 MERGE, 7.8.44 SORT) (GnuCOBOL project (GNU))
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress