Programming Tutorials

What is Referential Integrity in databases?

By: Peter den Haan in JDBC Tutorials on 2008-12-27  

Take the example of the Book database as shown below.

Table

Column

Key

Book

ID

Primary key

Title

Not a key field

Price

Not a key field

Author

ID

Primary key

Author_Name

Not a key field

Contribution

ID

Primary key

Title_ID

Foreign key

Author_ID

Foreign key

What happens when you start manipulating the records in your tables? You can edit the book information at will without any ill effects, but what would happen if you needed to delete a title? The entries in the Contribution table will still link to a nonexistent book. Clearly you can't have a contribution detail without the associated book title being present. So, you must have a means in place to enforce a corresponding book title for each contribution. This is the basis of enforcing referential integrity. You can enforce the validity of the data in this situation in two ways. One is by cascading deletions through the related tables; the other is by preventing deletions when related records exist.

Note 

Referential integrity prevents inconsistent data from being created in the database by ensuring that any data shared between tables remains consistent. To put it another way, it ensures that the soundness of the relationships remains intact.

Database applications have several choices available for enforcing referential integrity, but if possible, you should let the database engine do its job and handle this for you. Database engines allow you to use declarative referential integrity. You specify a relationship between tables at design time, indicating if updates and deletes will cascade through related tables. If cascading updates are enabled, changes to the primary key in a table are propagated through related tables. If cascading deletes are enabled, deletions from a table are propagated through related tables.

Before you go ahead and enable cascading deletes on all your relationships, keep in mind that this can be a dangerous practice. If you define a relationship between the Author table and the Title table with cascading deletes enabled and then delete a record from Author, you'll delete all Title table records that come under this category. Be cautious, or you may accidentally lose important data.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in JDBC )

Latest Articles (in JDBC)