Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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.

  • Intermediate
  • 20 minutes
  • Examples run with GnuCOBOL 3.2 and Python 3.14.8
  • By MySmartCoPilot
Free core, Pro depth: 8 of 20 minutes free
Free: SORT with USING and GIVING orders a whole file by its keys · Procedures and MERGE replace either end of the sort · Practise: keys, ends and order. With a pass: 2 in-depth parts and 3 interview answers, about 12 minutes.

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:

arrivals.txt: eight transactions in the order they arrived Text · arrivals.txt
BR02AC0004C000001250001
BR01AC0002D000012500002
BR01AC0001C000250000003
BR02AC0004D000030000004
BR01AC0002D000012500005
BR03AC0006D000000999006
BR01AC0001D000004999007
BR03AC0007D000150000008
sortkeys.cob: three keys, duplicates kept in order COB · sortkeys.cob
       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.
The eight transactions after the sort Python · sortkeys_session.py
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:

Interactive · stage by stage How the three keys of sortkeys.cob order the eight transactions Step down the column. Each key decides only among records that the keys above it left equal.
How the three keys of sortkeys.cob order the eight transactions, step 6 of 6. Showing USING arrivals.txt, Key 1: SR-BRANCH, Key 2: SR-ACCT, Key 3: SR-AMOUNT, Equal on every key, GIVING TXNOUT. In focus: GIVING TXNOUT.USING arrivals.txt8 records, arrival orderKey 1: SR-BRANCHascendingKey 2: SR-ACCTascending, within a branchKey 3: SR-AMOUNTlargest first per accountEqual on every keykept in arrival orderGIVING TXNOUTSORT-RETURN 00

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. 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.
  2. 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.
  3. The account. Within BR01 the account decides next, so the two AC0001 records come before the two AC0002 records.
  4. 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.
  5. Equal keys. Records 002 and 005 are both BR01, AC0002 and 125.00. WITH DUPLICATES IN ORDER keeps them as they arrived, 002 first.
  6. 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

  1. Question 1 of 2 After sortkeys.cob, which record is the second line of TXNOUT?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: BR01 AC0001, the 49.99 debit that arrived seventh

    The keys decide in order: branch, then account, then amount, largest first. Arrival order only breaks ties between records equal on every key.

  2. Question 2 of 2 Records 002 and 005 have the same branch, account and amount. What does WITH DUPLICATES IN ORDER do with them?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Keeps them in their input order, 002 before 005

    Records equal on every key need a rule for their order. WITH DUPLICATES IN ORDER gives the input order; without it, any order is allowed.

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

  1. Question 1 of 2 A job needs only the debits of a file in branch order, written to a new file. Which form of SORT fits?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: An INPUT PROCEDURE that RELEASEs only the debits, with GIVING for the output file

    Choose the end that does the work: an INPUT PROCEDURE decides what is sorted, an OUTPUT PROCEDURE what is done with the sorted records.

  2. Question 2 of 2 What must be true of the files a MERGE reads?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Each is already sorted on the same keys the MERGE names

    A merge only interleaves records that are already in order, which is why it needs no input procedure and why its inputs must be sorted first.

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.

  1. Question 1 of 6 In ON ASCENDING KEY SR-BRANCH SR-ACCT, which key decides first?

    Choose one answer.

    Show the answer: Question 1 of 6

    Answer: SR-BRANCH, the leftmost key named

    Keys decide from left to right, major to minor, and each later key matters only between records the earlier keys left equal.

  2. Question 2 of 6 Without ON DESCENDING KEY SR-AMOUNT, how would BR02 AC0004's two records come out of sortkeys.cob?

    Choose one answer.

    Show the answer: Question 2 of 6

    Answer: In arrival order, 12.50 (001) before 300.00 (004), since they would then be equal on every key

    Every key added changes the order only among records the other keys left equal. Here removing the amount key leaves the two records tied, and the tie keeps their arrival order.

  3. Question 3 of 6 What does SORT-RETURN hold after a SORT that worked?

    Choose one answer.

    Show the answer: Question 3 of 6

    Answer: 0

    Test SORT-RETURN after every SORT and MERGE: 0 means the output can be used.

  4. Question 4 of 6 A program opens TXN-IN to count its records and then runs SORT ... USING TXN-IN without closing it. What is wrong?

    Choose one answer.

    Show the answer: Question 4 of 6

    Answer: The USING file must not be open when the SORT starts, because the sort opens and closes it itself

    With USING and GIVING the sort owns the files. A program that needs to look at the records first uses an INPUT PROCEDURE, which opens, reads and closes the file itself.

  5. Question 5 of 6 A job needs only branch totals of a large file, never the sorted file itself. Which design does the least work?

    Choose one answer.

    Show the answer: Question 5 of 6

    Answer: SORT ... USING the file with an OUTPUT PROCEDURE that RETURNs the records and prints a total at each change of branch

    An OUTPUT PROCEDURE is the right end when the sorted records are only a step towards something else, such as a report.

  6. Question 6 of 6 The counter and online transactions arrive as two files, each sorted by branch and account. Why MERGE them rather than SORT ... USING both files?

    Choose one answer.

    Show the answer: Question 6 of 6

    Answer: Both give the same order, but MERGE only interleaves records that are already in order, so it does less work

    MERGE is the cheap way to join sorted files. It depends on its inputs being in order, which is why the order of each input is checked.

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.

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:

  1. 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.

  2. 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?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  3. 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.

    Model answer, Pro. First step and follow-ups

  4. 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?

    Model answer, Pro. First step and follow-ups

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.

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.