Friday, April 15, 2011

BULK COLLECT %FOUND and %NOTFOUND behaviour

When using the BULK COLLECT feature in PL/SQL, a lot of programmers get confused on using the %FOUND and %NOTFOUND in their code. As it is said multiple times (On various sites by various people), it seems better to avoid this by using .count, but I think it is good to point out the behaviour of %FOUND and %NOTFOUND in these cases.

Usually, you will have a code block similar to this:

  OPEN c_cur;
  LOOP
    FETCH c_cur BULK COLLECT INTO t_cur [limit <n>];
    l_found := c_cur%FOUND;
    CLOSE c_dual;
    [PL/SQL code here...]
    EXIT WHEN NOT l_found;
  END LOOP;

When you are determined to use %FOUND or %NOTFOUND, note the meaning of these when using BULK COLLECT:
  • %FOUND will return TRUE if exactly [limit] rows were retrieved



  • If %FOUND returns TRUE than there might be more rows to be fetched



  • %FOUND will return FALSE if less than [limit] rows were retrieved



  • %FOUND will always return FALSE if [limit] is not set (you retrieve less than unlimited rows)



  • %NOTFOUND will always return the opposite as %FOUND (as is to be expected...)
  • 3 comments:

    1. Nice one. I was just observing the odd behaviour of FOUND with BULK COLLECT (and no LIMIT clause) and found your post on it. Good to know in case it comes up on the exam! Thanks.

      ReplyDelete
    2. Thanks! This is good information.

      ReplyDelete
    3. This comment has been removed by a blog administrator.

      ReplyDelete