SORT Statement

The SORT statement causes a set of records or table elements to be arranged in a user-specified sequence.

For sorting files, the SORT statement accepts records from one or more files, sorts them according to the specified keys, and makes the sorted records available either through an output procedure or in an output file. The maximum number of USING or GIVING files is 32.

For sorting tables, the SORT statement sorts table elements according to specified table keys.

SORT Statement - Format 1 - File

Read syntax diagramSkip visual syntax diagramSORT Statement - Format 1 - FileSORTfile-name-1ONASCENDINGDESCENDINGKEYdata-name-1WITHDUPLICATESIN ORDERCOLLATINGSEQUENCEISalphabet-name-1USINGfile-name-2input procedure phraseGIVINGfile-name-3output procedure phrase
Read syntax diagramSkip visual syntax diagramSORTfile-name-1ONASCENDINGDESCENDINGKEYdata-name-1WITHDUPLICATESIN ORDERCOLLATINGSEQUENCEISalphabet-name-1USINGfile-name-2input procedure phraseGIVINGfile-name-3output procedure phrase
input procedure phrase
Read syntax diagramSkip visual syntax diagramINPUT PROCEDUREISprocedure-name-1THROUGHTHRUprocedure-name-2
output procedure phrase
Read syntax diagramSkip visual syntax diagramOUTPUT PROCEDUREISprocedure-name-3THROUGHTHRUprocedure-name-4
Read syntax diagramSkip visual syntax diagram

Format 1 SORT statements can appear anywhere in the PROCEDURE DIVISION except in a Declarative Section.

SORT statement - Format 2 - Table

Read syntax diagramSkip visual syntax diagramSORT statement - Format 2 - TableSORTdata-name-2ONASCENDINGDESCENDINGKEYdata-name-1WITHDUPLICATESINORDERCOLLATINGSEQUENCEIS alphabet-name-1
Read syntax diagramSkip visual syntax diagramSORTdata-name-2ONASCENDINGDESCENDINGKEYdata-name-1WITHDUPLICATESINORDERCOLLATINGSEQUENCEIS alphabet-name-1

Format 2 SORT statements can appear anywhere in the PROCEDURE DIVISION.

file-name-1
The name given in the SD entry that describes the records being sorted.

Null-capable fields are supported, but null values are only supported for DATABASE files that have ALWNULL specified on their ASSIGN clause. If ALWNULL is not specified, the SORT operation will fail, and file status of 90 will be returned if a field contains a null value.

data-name-2
Specifies a table data-name that is subject to the following rules:
  • data-name-2 must have an OCCURS clause in the data description entry.
  • data-name-2 can be qualified.
  • data-name-2 can be subscripted. The rightmost or only subscript of the table must be omitted or replaced with the word ALL.

The number of occurrences of table elements that are referenced by data-name-2 is determined by the rules in the OCCURS clause. The sorted table elements are placed in the same table that is referenced by data-name-2.