Deleting Secondary Database Records
Prev | Chapter 6. Secondary Databases | Next

## Deleting Secondary Database Records

In general, you can not modify a secondary database directly. In order to modify a secondary database, you should modify the primary database and simply allow JE to manage the secondary modifications for you.

However, as a convenience, you can delete `SecondaryDatabase` records directly. Doing so causes the associated primary key/data pair to be deleted. This in turn causes JE to delete all `SecondaryDatabase` records that reference the primary record.

You can use the `SecondaryDatabase.delete()` method to delete a secondary database record. Note that if your database supports duplicate records, then only the first record in the matching duplicates set is deleted by this method. To delete all the duplicate records that use a given key, use a `SecondaryCursor`.

### Note

`SecondaryDatabase.delete()` causes the previously describe delete operations to occur only if:

- the `SecondaryKeyCreator.createSecondaryKey()` method returns `true` (see Implementing Key Creators for information on this interface and method).

- the primary database is opened for write access.

If either of these conditions are not met, then no delete operations can be performed on the secondary database.

For example:

    package com.sleepycat.examples.je.gettingStarted;

    import com.sleepycat.je.DatabaseEntry;
    import com.sleepycat.je.DatabaseException;
    import com.sleepycat.je.OperationStatus;
    import com.sleepycat.je.SecondaryDatabase;

    ...
    try {
        // Omitting all database and environment opens
        ...

        String searchName = "John Doe";
        DatabaseEntry searchKey =
            new DatabaseEntry(searchName.getBytes("UTF-8"));

        // Delete the first secondary record that uses "John Doe" as
        // a key. This causes the primary record referenced by this secondary
        // record to be deleted.
        OperationStatus retVal = mySecondaryDatabase.delete(null, searchKey);
    } catch (Exception e) {
        // Exception handling goes here
    }

Prev | Up | Next
Reading Secondary Databases | Home | Using Secondary Cursors