-
Website
http://awads.net/wp/ -
Original page
http://awads.net/wp/2007/04/10/no_data_found-gotcha/ -
Subscribe
All Comments -
Community
-
Top Commenters
-
jgarry
3 comments · 1 points
-
Andy C
22 comments · 47 points
-
dahowlett
1 comment · 2 points
-
Don Seiler
9 comments · 1 points
-
davidhaimes
4 comments · 3 points
-
-
Popular Threads
Here's one that has probably bitten a few people.
The count() function does not raise a no_data_found error when no rows are returned, even when the table is empty.
SQL>create table js ( x integer);
Table created.
SQL>
SQL>declare
2 v_x integer;
3 begin
4 select count(*) into v_x from js;
5 dbms_output.put_line(v_x);
6 end;
7 /
0
PL/SQL procedure successfully completed.
Thanks Jared. I have been bitten with this "gotcha" when I first started with PL/SQL. Then, I learned that a SELECT INTO statement that calls a SQL aggregate function, such as COUNT(*) or AVG(), always returns a value or a null. Aggregate functions are guaranteed to return a single value, even if no "data is found".
I often do this sort of thing...
select nvl(max(col), 'DEFAULT_VALUE') into l_foo from table_name where x='BLAH';
In this case when there is no value I set a default and don't get the error. In the event that there is more than one value I only get one (I usually only implement this when that is very unlikely).
<ul>
<li>Ethan</li>
</ul>
Using nvl() ensures that your query will retrieve a non-null value.
It does not prevent any error condition though, as there would not be on.
select max(x) from js
where js is an empty table will not raise an error.
Actualy there is a way to cause a COUNT() query to raise the NO_DATA_FOUND exception :
if you add a group by clause to the query, e.g.,
SQL> DECLARE
2 l_count number;
3 BEGIN
4 select count()
5 into l_count
6 from all_objects
7 where 1 =0
8 group by 1;
9 DBMS_OUTPUT.put_line ('RESULT = '||l_count);
10 EXCEPTION
11 when NO_DATA_FOUND then
12 DBMS_OUTPUT.put_line ('Query returned no data!');
13 END;
14 /
Query returned no data!
PL/SQL procedure successfully completed
Follow Up my own comment :
I'd like to note that in case of adding a group by clause to such a query, you should also deal with a possibility of too_many_rows - if the query actualy succeeds....
Raising NO_DATA_FOUND on subscription error. It seems the developers were not busy enough to create an own out_of_bound exception for it
Karl
Simon,
what do you mean by " too_many_rows - if the query actualy succeeds…."
I took off the "1 =0" and it ran with no problem.