Learn it on Mainframe Path. Do it with Mainframe KIT.Learn on Mainframe Path ▸
Mainframe KIT ● Nothing leaves this tab

DFSORT: how do I sort by two fields?

List the major key first, then the minor key, in one SORT statement.

Checked against IBM documentation

THE SHORT ANSWER

Put both fields in one SORT FIELDS operand, four values each: position, length, format, and A or D. DFSORT examines the major control field first, so it must be written first; the minor fields follow it.

Steps

  1. Find each field's position and length. The first byte of a fixed-length record is position 1. For a variable-length record the first data byte is position 5, because the RDW takes the first 4.
  2. Pick the format of each field. CH is character, ZD zoned decimal, PD packed decimal, BI binary, FI fixed-point.
  3. Write the keys in order of importance. SORT FIELDS=(p,m,f,s,p,m,f,s): the major key first, then the minor key. Use A for ascending and D for descending.
  4. Add the DD statements. SORTIN is the input, SORTOUT the output, SYSIN holds the control statement.
  5. Check the statement before you run it. Paste it into the DFSORT helper to read it back in plain English.

Worked example: state ascending, then amount descending

Records of 15 bytes: name in 1-8, state in 9-10, amount in 12-15. The job step:

//SORT1    EXEC PGM=ICEMAN
//SYSOUT   DD SYSOUT=*
//SORTIN   DD DSN=MY.INPUT.DATA,DISP=SHR
//SORTOUT  DD DSN=MY.OUTPUT.DATA,DISP=(NEW,CATLG),
//            SPACE=(TRK,(1,1)),RECFM=FB,LRECL=15
//SYSIN    DD *
  SORT FIELDS=(9,2,CH,A,12,4,ZD,D)
/*

INPUT
  SMITH    NY 0250
  JONES    CA 0900
  BROWN    NY 0975
  GREEN    CA 0120
SORTED
  JONES    CA 0900
  GREEN    CA 0120
  BROWN    NY 0975
  SMITH    NY 0250

CA comes before NY (major key, ascending), and inside each state the larger amount comes first (minor key, descending).

Sources, checked : SORT control statement, z/OS 3.2.0 DFSORT; Program DD statements, z/OS 3.2.0 DFSORT; System DD statements, z/OS 3.2.0 DFSORT; SORT cataloged procedure, z/OS 3.2.0 DFSORT. Explanations are in our own words; the worked example is invented. Confirm against IBM documentation before changing production systems. mainframekit.com/guides/dfsort-sort-by-two-fields/

Use your browser's Print command for a one-page copy.