Handling Indexed Files in COBOL
Handling Indexed Files (Basic Overview)
Welcome! In previous lessons, you've learned how to create, write to, read from, and append records to sequential files in COBOL. In this lesson, we are taking a deeper dive into a more powerful concept: handling indexed files. Mastering indexed files will enable you to perform faster searches, updates, and deletions based on key fields, making your programs more efficient and scalable.
What You'll Learn
In this lesson, you will learn how to create and manipulate indexed files in COBOL. Indexed files allow you to access records randomly, which is a big advantage over sequential files when dealing with large datasets. For this lesson, we will use a practical example where you write a customer record to an indexed file and then retrieve it based on an account number.
Defining Indexed Files
First we define the file structure and environment settings:
In the above code snippet, we define an indexed file named IndexedFile with the ORGANIZATION IS INDEXED clause. The RECORD KEY IS Account-Number clause specifies that the Account-Number field will be used as the key for random access.
Writing to and Reading from Indexed Files
Next, we write a customer record to the indexed file:
In the above code, we open the indexed file in output mode and write a customer record with the name "Michael Johnson," account number 8765432109, and account balance 3200.25.
Then we read the customer record based on the account number:
In this code snippet, we open the indexed file in input mode and read the customer record based on the account number 8765432109. If the record is found, we display the customer name, account number, and account balance. Otherwise, we display a message indicating that the record was not found.
If we specify an invalid account number in the READ statement with KEY IS <invalid key>, the INVALID KEY clause will be executed, and the message "Record not found" will be displayed.
Let's note, that in the KEY IS clause, we have to specify the key field exactly as it is defined in the FILE-CONTROL section of the file with the RECORD KEY clause - in this case, the key field is Account-Number. For example KEY IS Some-Variable will not work, even if it has the same value as Account-Number. Similarly something like KEY IS 8765432109 will not work, as it is not a valid key field.
