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.
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:
- The table must be ordered by the same key used in the
WHENcondition. - The order must match the
ASCENDING KEYorDESCENDING KEYdeclared on the table. - Only populated occurrences may participate. An
OCCURS DEPENDING ONcount, or a separately maintained active-row limit, must be correct.
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:
- Empty table: confirm the active count is zero and the lookup follows the expected no-route path.
- First and last valid keys: catch index and boundary mistakes.
- Key below, between, and above valid ranges: verify
AT ENDhandling. - A deliberately out-of-order pair: prove the load validation rejects it before lookup.
- A duplicate key: prove the stated duplicate rule or rejection path.
- A key containing lowercase letters, blanks, or non-display values when the feed can contain them: validate normalization rules before comparing.
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
- Identify the table's source, effective copybook/layout version, load routine, and declared sort direction.
- Confirm the active-row count cannot exceed the table maximum and is reset for each run or transaction as appropriate.
- Obtain a sanitized count of loaded rows, rejected rows, and lookup misses; do not attach business records to tickets.
- Check whether the table is loaded once, shared across transactions, or changed after load. Concurrency and lifecycle rules vary by application.
- Establish what a missing or duplicate key should do: reject, default, suspend, or escalate. Do not silently route to a convenient fallback.
- Test the correction with controlled ordered and deliberately disordered input before promotion.
- For a batch problem, determine whether prior records were already routed or downstream outputs were delivered before considering restart. Do not blindly rerun an updating flow.
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.