COBOL by Example: Indexed Files
Working with indexed files for random access by primary key, implementing ORGANIZATION IS INDEXED with RECORD KEY, using ACCESS MODE RANDOM or DYNAMIC, handling INVALID KEY errors, and understanding VSAM KSDS datasets on mainframes.
Code
IDENTIFICATION DIVISION.
PROGRAM-ID. INDEXED-FILES.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMP-FILE ASSIGN TO "emp.dat"
ORGANIZATION IS INDEXED
ACCESS MODE IS RANDOM
RECORD KEY IS EMP-ID.
DATA DIVISION.
FILE SECTION.
FD EMP-FILE.
01 EMP-REC.
05 EMP-ID PIC 99.
05 EMP-NAME PIC X(10).
PROCEDURE DIVISION.
OPEN INPUT EMP-FILE.
MOVE 15 TO EMP-ID.
READ EMP-FILE
INVALID KEY DISPLAY "Record 15 not found"
NOT INVALID KEY DISPLAY "Found: " EMP-NAME
END-READ.
CLOSE EMP-FILE.
STOP RUN.Explanation
Indexed files allow you to access records directly using a primary key, without reading all preceding records. This is critical for database-like performance. You must specify ORGANIZATION IS INDEXED and define a RECORD KEY which must be a field within the file record.
With ACCESS MODE IS RANDOM, you can set the key value and issue a READ command to fetch that specific record. The INVALID KEY clause handles cases where the record doesn't exist. You can also use ACCESS MODE IS DYNAMIC to mix sequential and random access.
On mainframes, these are typically VSAM KSDS (Key Sequenced Data Sets). They are the backbone of many legacy transaction processing systems, allowing for rapid retrieval of customer data, account balances, and inventory items.

