COBOL

COBOL SEARCH ALL: Prove the Table Is Ordered Before Using Binary Search

`SEARCH ALL` is attractive because it can locate a row in a large COBOL table with fewer comparisons than a sequential `SEARCH`. Its hidden precondition is more important than its speed: the active rows must already be ordered exactly as the search key and sort direction expect.

InputValidationProcessingOutput
Original DBala learning flow — a visual summary of this article’s practical decision path.

SEARCH ALL is attractive because it can locate a row in a large COBOL table with fewer comparisons than a sequential SEARCH. Its hidden precondition is more important than its speed: the active rows must already be ordered exactly as the search key and sort direction expect.

This tutorial shows how to build that proof into a small routing-table lookup. The example is fictional, but the checks apply to in-memory reference tables loaded from files, DB2 rows, parameters, or copybooks.

Why a valid program can return the wrong business result

A binary search does not inspect every row. It compares the requested key with a midpoint, then discards half of the remaining range. That decision is correct only if keys increase or decrease consistently throughout the used part of the table.

If one row is out of order, SEARCH ALL may report AT END for a key that is present. It can also find a row in a test run and fail only for particular keys, which makes the defect look like bad input or an intermittent table-load issue.

Three details need to agree:

A successful compile, a normal return code, and a few successful lookups are not evidence that these conditions hold.

A compact routing-table pattern

Assume a batch program receives a three-character transaction code and uses a small table to select a route. The loader has already placed the active rows in ascending transaction-code order. The values are illustrative, not an interface layout to copy unchanged.

       WORKING-STORAGE SECTION.
       01  WS-ROUTE-COUNT             PIC 9(3) COMP-3 VALUE ZERO.
       01  WS-LOOKUP-CODE             PIC X(3).
       01  WS-ROUTE-FOUND             PIC X VALUE 'N'.
       01  WS-ROUTE-NAME              PIC X(12).

01 WS-ROUTE-TABLE.
05 WS-ROUTE-ROW OCCURS 1 TO 200 TIMES
DEPENDING ON WS-ROUTE-COUNT
ASCENDING KEY IS WS-ROUTE-CODE
INDEXED BY ROUTE-IX.
10 WS-ROUTE-CODE PIC X(3).
10 WS-ROUTE-NAME-TBL PIC X(12).

PROCEDURE DIVISION.
4000-FIND-ROUTE.
MOVE 'N' TO WS-ROUTE-FOUND
MOVE SPACES TO WS-ROUTE-NAME
SEARCH ALL WS-ROUTE-ROW
AT END
CONTINUE
WHEN WS-ROUTE-CODE (ROUTE-IX) = WS-LOOKUP-CODE
MOVE 'Y' TO WS-ROUTE-FOUND
MOVE WS-ROUTE-NAME-TBL (ROUTE-IX)
TO WS-ROUTE-NAME
END-SEARCH
.
```

If the active rows are A10, B20, C30, and D40, a lookup for C30 is meaningful. If a loader accidentally produces A10, C30, B20, D40, the table definition still says ascending, but the data does not obey it. SEARCH ALL has no general obligation to detect that contradiction.

The declaration is not an instruction to sort. It is a contract made by the program. The routine that loads the table is responsible for satisfying it.

Validate order where the table enters the program

The safest time to find disorder is during the load, before a business record is routed. Keep the previous active key and compare it with each new key. For an ascending table, each new key must be greater than the previous key; whether equal keys are permitted is a business rule that must be explicit.

       2000-LOAD-ROUTES.
           MOVE SPACES TO WS-PREVIOUS-CODE
           MOVE ZERO   TO WS-ROUTE-COUNT
           PERFORM UNTIL WS-END-OF-ROUTES = 'Y'
              READ ROUTE-FILE
                 AT END
                    MOVE 'Y' TO WS-END-OF-ROUTES
                 NOT AT END
                    IF ROUTE-CODE-IN NOT > WS-PREVIOUS-CODE
                       DISPLAY 'ROUTE TABLE NOT ASCENDING - LOAD REJECTED'
                       MOVE 'Y' TO WS-ROUTE-LOAD-ERROR
                    ELSE
                       ADD 1 TO WS-ROUTE-COUNT
                       MOVE ROUTE-CODE-IN
                         TO WS-ROUTE-CODE (WS-ROUTE-COUNT)
                       MOVE ROUTE-NAME-IN
                         TO WS-ROUTE-NAME-TBL (WS-ROUTE-COUNT)
                       MOVE ROUTE-CODE-IN TO WS-PREVIOUS-CODE
                    END-IF
              END-READ
           END-PERFORM
           .

Production code should use the site's approved error-reporting and stop/reject path rather than copying the DISPLAY. The point is to preserve evidence: which control source was used, how many rows were accepted, and the first key relationship that violated the declared order. Do not emit sensitive descriptions or entire input records merely to diagnose a lookup.

If duplicate transaction codes are valid, change the comparison deliberately. For example, ROUTE-CODE-IN < WS-PREVIOUS-CODE permits duplicates, but then the lookup contract must state which duplicate is returned and why. Binary search is not a substitute for a duplicate-resolution rule.

Choosing SEARCH or SEARCH ALL

Use the search method as a design decision, not a performance reflex.

| Situation | Safer choice | Reason |
| --- | --- | --- |
| Small table with no controlled ordering source | SEARCH | Sequential search does not rely on ordering. |
| Large reference table loaded from an ordered, validated source | SEARCH ALL | The ordering contract can be proved and lookup cost is lower. |
| Key can appear more than once | Design a duplicate rule first | Neither form defines the business meaning of an ambiguous key. |
| Table is modified after load | Revalidate or avoid binary search | An insert or update can invalidate the original order. |
| Lookup uses a composite business key | Define the full ordering key | Ordering by only the first component is insufficient for an equality search on both. |

For a few dozen rows, a sequential search may be clearer and entirely adequate. Measure only when response time or CPU evidence makes table lookup material. Replacing a readable SEARCH with SEARCH ALL without controlling the input order trades a visible loop for a harder support problem.

Failure cases worth testing

A useful unit or component test set includes more than a found and not-found case:

For alphanumeric keys, COBOL comparison follows the active collating sequence. Do not assume a local character ordering matches a spreadsheet, an ASCII service, or an upstream distributed application. If the source and runtime use different representations or conversion rules, test the actual converted keys in an approved environment.

What to verify before changing a production lookup

Practical takeaway

SEARCH ALL is reliable when the table's ordering is treated as a verified input control, not as a comment in the data division. Validate the load, make duplicate handling explicit, and retain only the evidence needed to explain a miss. Then binary search becomes a predictable implementation choice instead of a source of selective production defects.

← Back to all articles