Hudzilla.org - the homepage of Paul Hudson
Contents > Databases > Subselects, views, and other advanced functions Wish List | Report Bug | About Me ]

9.19.3     Referential integrity

This is NOT the latest copy of this book; click here for the latest version.

When used properly, referential integrity is a powerful tool to help you keep your tables in order. The two main uses are:

  1. to stop you deleting rows that are referenced elsewhere

  2. to allow you to delete a row in table A and have the DBMS automatically delete all other rows in other tables that reference that row

We could rewrite our Orders table definition to mark Customer as a foreign key of the ID field in the Customers table by doing this:

CREATE TABLE Orders (ID INT, Customer INT, Purchase CHAR(255), FOREIGN KEY (Customer) REFERENCES Customers(ID));

With that in place, rows in the Orders table are explicitly tied to customers in the Customers table. Note that some DBMSs may require you to make the foreign key (Customer, in the example) indexed. For example, try executing the following query:

mssql_query("DELETE FROM Customers WHERE ID = 1;");

With the foreign key in place, the default action is to stop people from making a call like this as it would leave rows in the Orders table pointing to a customer that doesn't exist. So, if you try that query, you should get an error like this one: "DELETE statement conflicted with COLUMN REFERENCE constraint 'FK__Orders__Customer__76969D2E'. The conflict occurred in database 'phpdb', table 'Orders', column 'Customer'."

The constraint name (FK__Orders__Customer__76969D2E) is randomly generated when the foreign key link is created, but what it is trying to say is that you attempted to delete a key that has rows relying upon it, which is a no-no. However, this has amply demonstrated the first helpful use of referential integrity: to stop you deleting rows that are referenced elsewhere.

By modify the query again, we can get the DBMS to perform the opposite action - enforce integrity by deleting rows that are referenced. Here is the new CREATE TABLE line:

CREATE TABLE Orders (ID INT, Customer INT, Purchase CHAR(255), FOREIGN KEY (Customer) REFERENCES Customers(ID) ON DELETE CASCADE);

The "ON DELETE CASCADE" is the important part, as it instructs the DBMS to "cascade" deletes when the referenced row is deleted. That is, if a customer gets deleted, all their entries in Orders will be deleted also. This can be demonstrated with the same query as before:

mssql_query("DELETE FROM Customers WHERE ID = 1;");

This time Paul's entry in Customers is deleted without error, and all three of his rows in Orders are deleted also, thus leaving the database consistent.

There is one final use for referential integrity, however it is not supported in all DBMSs. Using the syntax ON DELETE SET NULL, the foreign key field will be set to NULL if possible if the referenced row is deleted. This has the effect of keeping the data intact, but saying that the row it referenced no longer exists, however it will not work if the referenced row has been declared NOT NULL. There are not many situations where SET NULL is recommended, and, thanks to it not being available on all DBMSs, it is generally best avoided.





<< 9.19.2 Views   9.20 Summary >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Be the first to add a comment to this chapter!



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is one plus three?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow