Friday 26 August 2011

Why doesn't an UPDATE raise the NO_DATA_FOUND exception

Question:
Why doesn't an UPDATE raise the NO_DATA_FOUND exception?
Answer:
Arun, a number of people have asked that question over the years. At first glance, it seems like an inconsistency. I try to query some rows and if none are found, I get an error. Yet if I try to update some rows and none are found, I don't receive an error. Instead, SQL%ROWCOUNT is set to 0.
Certainly, Oracle as well as the ANSI standards committee could have specified that NO_DATA_FOUND be raised when no rows are updated. I can only speculate as follows:
• When I execute an update statement I am saying "Update all the rows that satisfy this WHERE clause, or all rows if the WHERE clause is missing." If my WHERE clause identifies no rows, that isn't really an error; the UPDATE simply followed your command and updated the rows you specified—of which there were none.
• When you execute a query, you want to retrieve data. That's the point of the query. So if I don't get any back, that is an exceptional situation and Oracle raises the exception to indicate that fact.
Of course, another is simply "That's the way the ANSII standard goes..."
By the way, I suggest that you always place your queries inside a function so that you can trap the NO_DATA_FOUND exception and decide if you want to propagate that exception out to the enclosing block. You could take the same approach with UPDATE: put it inside a procedure and have it raise an exception when SQL%ROWCOUNT is set to 0, if that is the behavior you want/need in your application.
I recommend functions and procedures, by the way, so that you are more easily able to reuse those SQL statements.

No comments:

Post a Comment