sqloracle-databaseexceptionplsqlora-01403

Why is no_data_found ORA-01403 an exception in Oracle?


If the SELECT INTO statement doesn't return at least one row, ORA-01403 is thrown.

For every other DBMS I know this is normal on a SELECT. Only Oracle treats a SELECT INTO like this.

CREATE OR REPLACE PROCEDURE no_data_proc IS
   dummy dual.dummy%TYPE;
BEGIN
  BEGIN 
     SELECT dummy  
       INTO dummy
       FROM dual
      WHERE dummy = 'Y';   
  EXCEPTION 
     WHEN no_data_found THEN
        dbms_output.put_line('Why is this needed?');
  END;
END no_data_proc;

Why?

In my opinion you don't need this exception really. It is too much overhead. Sometimes it is handy but you have to write a whole BEGIN, EXCEPTION, WHEN, END Block.

Are there any essential reasons I don't see?


Solution

  • The exception block is not needed, you might use it or not, depending on the context.

    Here you are actively ignoring the exception (the procedure will return successfully) but most of the time if you're doing a SELECT INTO you want it to fail if it doesn't return a row, consider:

    PROCEDURE update_employee_salary (p_empno) IS
       l_salary NUMBER;
    BEGIN
       SELECT sal INTO l_salary FROM emp WHERE empno = p_empno FOR UPDATE;
       /* do something with emp data */
    END;
    

    Here I want my function to fail if it is called with an empno that doesn't exist in the EMP table. I might catch the exception to raise a meaningful error message (with raise_application_error) but most of the time I'm happy with the ORA-01403.

    In general, the only exceptions you should catch are the expected exceptions (i.e. this should not be the standard to catch all ORA-01403, or all exceptions for that matter).