Sub topic 13
Handling NO_DATA_FOUND and TOO_MANY_ROWS
This chapter assumes you can write an anonymous PL/SQL block with a declaration, executable, and exception section. It also assumes you have used SELECT ... INTO and %TYPE, and can run blocks in SQL*Plus, SQL Developer, or SQLcl against the HR sample schema. The goal is to handle the two errors that SELECT INTO raises most often.
Why SELECT INTO raises exceptions
A SELECT INTO statement in PL/SQL expects the query to return exactly one row. The row's columns are copied into the variables in the INTO list. Two things can break that rule:
- The query returns no rows. PL/SQL raises
NO_DATA_FOUND. - The query returns more than one row. PL/SQL raises
TOO_MANY_ROWS.
Plain SQL does not treat either case as an error. An empty result set or a large one is normal there. The error exists because a scalar variable or a record holds one row, and PL/SQL will not pick a row for you.
| Exception | Error message | SQLCODE | Cause |
|---|---|---|---|
| `NO_DATA_FOUND` | ORA-01403: no data found | +100 | The query matched zero rows |
| `TOO_MANY_ROWS` | ORA-01422: exact fetch returns more than requested number of rows | -1422 | The query matched two or more rows |
Both are predefined exceptions. You can name them in a WHEN clause without declaring them.
Seeing the unhandled error
Run a lookup for an ID that does not exist, with no exception section:
SET SERVEROUTPUT ON
DECLARE
v_last_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO v_last_name
FROM employees
WHERE employee_id = -1;
DBMS_OUTPUT.PUT_LINE('Found: ' || v_last_name);
END;
/Nothing prints. The client reports ORA-01403: no data found along with ORA-06512 and a line number. ORA-06512 is a stack line that points at where the exception was raised. When a block raises an exception and has no handler, execution jumps out of the block. The remaining statements are skipped, so the PUT_LINE call never runs.
Writing handlers
A handler lives in the EXCEPTION section, after the executable statements. Each WHEN clause names an exception, followed by the statements to run.
SET SERVEROUTPUT ON
DECLARE
v_last_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO v_last_name
FROM employees
WHERE department_id = 50;
DBMS_OUTPUT.PUT_LINE(v_last_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee in that department.');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Several employees are in that department.');
END;
/In the standard HR schema, department 50 has many employees, so the second handler runs. Three rules apply:
- PL/SQL checks the
WHENclauses from top to bottom and runs the first one that matches. - Only one handler runs per exception. After it finishes, the block ends. Control does not return to the statement after the failed
SELECT. - A block that handles the exception completes normally. The caller sees no error.
The second rule matters most in practice. If your block has several statements after the SELECT INTO, a handler in the same block cannot resume them. Use a nested block (below) when you need to recover and continue.
Do not rely on the variables after a failure
When SELECT INTO raises either exception, Oracle documents the INTO variables as undefined. A variable may keep its old value, or a TOO_MANY_ROWS error may leave it holding data from a row. Do not read it in the handler. Assign an explicit value instead.
Recovering and continuing with a nested block
To apply a default and keep going, put the SELECT INTO in its own block. The inner handler runs, the inner block ends normally, and the outer block continues.
SET SERVEROUTPUT ON
DECLARE
v_last_name employees.last_name%TYPE;
BEGIN
BEGIN
SELECT last_name
INTO v_last_name
FROM employees
WHERE employee_id = -1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_last_name := 'Unknown';
END;
DBMS_OUTPUT.PUT_LINE('Name: ' || v_last_name);
END;
/The output is Name: Unknown. This pattern also solves a diagnostic problem. If one block contains three SELECT INTO statements, a single NO_DATA_FOUND handler cannot tell which one failed. Wrapping each in its own block lets each handler give a specific response.
Fixing TOO_MANY_ROWS at the source
For TOO_MANY_ROWS, catching the exception is often the wrong fix. The error usually means the query is not selective enough. Decide what you actually want, then change the query.
| Intent | Approach |
|---|---|
| Exactly one row should match, such as a primary key lookup | Filter on a unique column. Treat `TOO_MANY_ROWS` as a data or logic bug and let it surface or log it. |
| Any one row is acceptable | Add `FETCH FIRST 1 ROW ONLY` (Oracle Database 12c and later). |
| The highest or lowest row is wanted | Add `ORDER BY` with `FETCH FIRST 1 ROW ONLY`. |
| You want a summary of all rows | Use an aggregate such as `COUNT`, `MAX`, or `SUM`. |
| You need every row | Use a cursor `FOR` loop instead of `SELECT INTO`. |
This example picks the highest-paid employee in department 50:
SET SERVEROUTPUT ON
DECLARE
v_last_name employees.last_name%TYPE;
v_salary employees.salary%TYPE;
BEGIN
SELECT last_name, salary
INTO v_last_name, v_salary
FROM employees
WHERE department_id = 50
ORDER BY salary DESC
FETCH FIRST 1 ROW ONLY;
DBMS_OUTPUT.PUT_LINE(v_last_name || ' earns ' || v_salary);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Department 50 has no employees.');
END;
/The ORDER BY makes the choice deterministic. Without it, "first row" is whichever row Oracle happens to return, and it can change between runs. Even with FETCH FIRST, NO_DATA_FOUND is still possible, because an empty department returns zero rows.
Aggregates never raise NO_DATA_FOUND
A query with an aggregate function and no GROUP BY always returns exactly one row, even if the WHERE clause matches nothing. COUNT returns 0. The others return NULL.
SET SERVEROUTPUT ON
DECLARE
v_max_salary employees.salary%TYPE;
v_count PLS_INTEGER;
BEGIN
SELECT MAX(salary), COUNT(*)
INTO v_max_salary, v_count
FROM employees
WHERE department_id = -1;
IF v_max_salary IS NULL THEN
DBMS_OUTPUT.PUT_LINE('No salaries found, row count = ' || v_count);
END IF;
END;
/This block raises no exception and prints No salaries found, row count = 0. Two consequences follow. A NO_DATA_FOUND handler around an aggregate query is dead code. And a NULL result is ambiguous: it can mean no rows matched, or it can mean rows matched and the column was NULL in all of them. Use COUNT(*) alongside the aggregate when you must tell the two apart.
Reporting details with SQLCODE and SQLERRM
Inside a handler, SQLCODE returns the numeric error code and SQLERRM returns the message text. They are useful when one handler covers several exceptions. Assign them to variables before using them in a SQL statement, because they cannot be referenced directly inside one.
SET SERVEROUTPUT ON
DECLARE
v_last_name employees.last_name%TYPE;
v_code PLS_INTEGER;
v_message VARCHAR2(512);
BEGIN
SELECT last_name
INTO v_last_name
FROM employees
WHERE department_id = 50;
EXCEPTION
WHEN NO_DATA_FOUND OR TOO_MANY_ROWS THEN
v_code := SQLCODE;
v_message := SQLERRM;
DBMS_OUTPUT.PUT_LINE('Lookup failed: ' || v_code || ' ' || v_message);
END;
/For department 50 this prints code -1422 and its message. WHEN A OR B lets one handler serve both exceptions.
Common mistakes
- Handling the exception in the wrong block. A handler only covers statements in its own block. An exception raised in the
DECLAREsection, for example in a variable initializer, skips that block's handlers and goes to the enclosing block. - Using
WHEN OTHERS THEN NULL. This silently swallows every error, including ones you did not expect. If you need a catch-all, log the error and re-raise it withRAISE. - Putting
WHEN OTHERSbefore specific handlers. Oracle rejects a block where a handler followsOTHERS, because the later one could never run. - Treating
NO_DATA_FOUNDas always an error. For an optional lookup, such as a manager who may not exist, a missing row is a normal result and a default value is the right response. - Assuming a unique-looking filter is unique. A lookup by
last_namemay work in test data and raiseTOO_MANY_ROWSin production when two people share a surname. - Expecting
NO_DATA_FOUNDfromUPDATEorDELETE. Those statements do not raise it when they affect zero rows. CheckSQL%ROWCOUNTafter the statement instead.
Exercises
Exercise
A block contains two statements, SELECT salary INTO vsalary ... WHERE employeeid = 999 and then DBMSOUTPUT.PUTLINE('Salary: ' || vsalary). Employee 999 does not exist. The block's exception section has a NODATA_FOUND handler that prints 'Missing'. What is printed, and does the Salary line run?
Show answer
Only 'Missing' is printed. When the SELECT INTO raises NODATAFOUND, control jumps to the handler. The block then ends, so the Salary line never runs. To continue after the failure, wrap the SELECT INTO in its own nested block with its own handler.
Exercise
You run SELECT MAX(salary) INTO vmax FROM employees WHERE departmentid = -1 inside a block that has a NODATAFOUND handler. Does the handler run? What does v_max contain, and how can you check whether any rows matched?
Show answer
The handler does not run. An aggregate query without GROUP BY always returns one row, so no exception is raised. v_max is NULL. To check whether rows matched, select COUNT(*) in the same query, which returns 0 when nothing matched.
Exercise
Rewrite SELECT lastname INTO vlastname FROM employees WHERE departmentid = 80 so it never raises TOOMANYROWS and returns the employee with the lowest employee_id. Which exception can still occur?
Show answer
Add ORDER BY employeeid and FETCH FIRST 1 ROW ONLY: SELECT lastname INTO vlastname FROM employees WHERE departmentid = 80 ORDER BY employeeid FETCH FIRST 1 ROW ONLY. NODATAFOUND can still occur if department 80 has no employees, so keep a handler for it.