Thursday, September 3, 2009

MULTIPLE KEYS (PRIMARY & ALTERNATE KEYS)

Sometimes the programmers need to assign more than one key fields in their records. An example could be a database where one wants to keep records for vehicles registered to a certain country. The Turkish vehicle plate numbering system is NOT suitable for using relative files because it contains alphabetic parts ( eg. 06 AHT 08) . As you might guess, this type of key values is very very suitable to be organized as an INDEXED file.

Having declared the "PLATE" field as the key field, now, given a plate number, a program which has declared an indexed file with RANDOM access mode, can find the corresponding record very quickly (if the does exist, this condition will also be detected very quickly).

Knowing that no two vehicles have the same plate number (unique), the plate number is certainly a very good choice for the key.

However, suppose that the program you have to write is also expected to find records for vehicles of a certain brand very quickly. Since the key is the plate number, the only way you can find "OPEL" brand vehicles by going through all the records (declare the access mode to be sequential and READ NEXT all records till the AT END condition raises) testing the BRAND field against the value given by the ýser ("OPEL" for instance).

With indexed files, there is a better solution : You can declare the BRAND field also to be a key; but AN ALTERNATE key!. The PRIMARY key will still be the plate numbers. Since there are many vehicles manufactured by OPEL in your database, you know that the ALTERNATE KEY values will not be uniqe. THIS IS ALLOWED IN COBOL. ONLY THE PRIMARY KEY HAS TO BE UNIQE. ALTERNATE KEYS CAN HAVE DUPLICATE VALUES.

You can declare as many alternate keys your program requires. More alternate keys you have, more extra data structures will be required and slower be your program. Therefore certain attention should be paid before assigning alternate keys. You should avoid unnecessary alternate keys.

When you have alternate keys, you declare them in the SELECT statement together with the PRIMARY key.

SELECT VEHICLES ASSIGN TO DISK "VEHICLES.DAT"

ORGANIZATION IS INDEXED

ACCESS MODE IS RANDOM

RECORD KEY IS PLATE

ALTERNATE KEY IS BRAND.

....

FD VEHICLES.

01 VEHICLE-REC.

02 PLATE PIC XXXXXXXXXX.

02 BRAND PIC X(20).

02 OWNER PIC X(32).

02 DATE-REGISTERED PIC 99999999.

02 ENGINE-NO PIC X(20).

02 CHASSIS-NO PIC X(20).

...

When you need to access the file with the primary key, you just move the key value to the primary key field of the record and issue a READ statement.

MOVE "06 AHT 08" TO PLATE.

READ VEHICLES INVALID KEY PERFORM NOT-FOUND.

When you need to access the file using an alternate key, you move an appropriate value to the alternate key you want to use and issue a READ statement in which you specify which key you want to use

MOVE "CHEVROLET" TO BRAND.

READ VEHICLES KEY BRAND INVALID KEY PERFORM NOT-FOUND.