The error ORA-01422: exact fetch returns more than requested number of rows is one of the most common exceptions encountered by developers working with Oracle PL/SQL. It occurs when a SELECT INTO statement retrieves more than one row, but the target variables can only hold a single value. Understanding why this happens and how to resolve it is fundamental for writing dependable, error-free database code Less friction, more output..
This article provides a thorough look to diagnosing, fixing, and preventing this specific error, covering everything from basic syntax mistakes to advanced bulk processing techniques.
Understanding the Root Cause
At its core, the SELECT INTO clause is designed for singleton selects—queries guaranteed to return exactly one row. When the SQL engine executes the query and finds two or more rows matching the WHERE clause, it cannot decide which row's data to assign to the variables. So naturally, it halts execution and raises the TOO_MANY_ROWS exception (error code ORA-01422).
The Mechanism Behind the Error
- Parsing & Execution: Oracle parses the
SELECTstatement. - Fetching: The cursor fetches the first row successfully.
- Validation: The cursor attempts to fetch a second row to verify uniqueness.
- Exception: Upon finding a second row, Oracle immediately raises
TOO_MANY_ROWSand rolls back the assignment for the first row (leaving target variables unchanged orNULL).
This strict behavior enforces data integrity, ensuring your logic does not silently proceed with arbitrary data when multiple matches exist The details matter here..
Common Scenarios Triggering ORA-01422
Identifying where the logic fails is the first step toward a fix. Here are the most frequent scenarios:
1. Missing or Insufficient WHERE Clause
The most basic cause is querying a table without a filter that guarantees uniqueness And it works..
-- Bad: Returns all employees in department 10
SELECT last_name, salary
INTO v_name, v_sal
FROM employees
WHERE department_id = 10; -- Multiple employees exist here
2. Non-Unique Column Filtering
Filtering by a column that lacks a Unique Constraint or Primary Key. Even if data looks unique today, the database engine cannot guarantee it tomorrow unless a constraint enforces it Small thing, real impact..
-- Risky: email might not be unique unless constrained
SELECT employee_id
INTO v_id
FROM employees
WHERE email = 'jdoe@example.com';
3. Implicit Cursors in Loops
Developers sometimes place a SELECT INTO inside a loop iterating over a driving cursor, forgetting that the inner query might return multiples for a specific iteration Most people skip this — try not to..
4. Data Quality Issues
Duplicate data entered due to missing constraints, failed ETL processes, or manual INSERT statements bypassing application logic.
Standard Solutions and Fixes
The solution depends entirely on why multiple rows exist and what your business logic dictates.
Solution 1: Enforce Uniqueness via Primary Key or Unique Constraint (Best Practice)
If the business rule dictates that only one row should exist, fix the data model, not just the code. Add a Primary Key or Unique Constraint.
ALTER TABLE employees ADD CONSTRAINT uk_emp_email UNIQUE (email);
Once the constraint exists, the SELECT INTO is safe. If a duplicate is inserted later, the database rejects it at the source (ORA-00001), which is far preferable to a runtime query error Worth knowing..
Solution 2: Refine the WHERE Clause
Add filters to narrow the result set to a single row. Use the Primary Key whenever possible.
-- Good: Primary Key guarantees 0 or 1 row
SELECT last_name, salary
INTO v_name, v_sal
FROM employees
WHERE employee_id = p_emp_id; -- PK lookup
Solution 3: Aggregate Functions (When "Any" Row Won't Do)
If you need a calculated value from multiple rows (e.g., total salary, max date, count), use aggregate functions. These always return exactly one row (even if the table is empty, they return NULL or 0, never raising NO_DATA_FOUND or TOO_MANY_ROWS).
-- Returns exactly 1 row: the sum
SELECT SUM(salary), COUNT(*)
INTO v_total_sal, v_emp_count
FROM employees
WHERE department_id = 10;
Solution 4: Deterministic Row Selection (FETCH FIRST / ROWNUM)
If multiple rows exist and you must pick one (e.g., "get the most recent order"), use explicit ordering and limiting clauses. Never rely on "natural order" (the order rows happen to be stored), as it is non-deterministic Took long enough..
Oracle 12c and later (ANSI Standard):
SELECT order_id
INTO v_latest_order
FROM orders
WHERE customer_id = p_cust_id
ORDER BY order_date DESC
FETCH FIRST 1 ROW ONLY;
Older Versions (Subquery with ROWNUM):
SELECT order_id
INTO v_latest_order
FROM (
SELECT order_id
FROM orders
WHERE customer_id = p_cust_id
ORDER BY order_date DESC
)
WHERE ROWNUM = 1;
Note: Applying ROWNUM = 1 in the main WHERE clause before the ORDER BY yields a random row. The subquery (inline view) forces ordering first.
Solution 5: Exception Handling (Defensive Coding)
If you cannot guarantee uniqueness via constraints or logic, catch the exception explicitly. This allows you to log the anomaly or apply a fallback rule Most people skip this — try not to..
DECLARE
v_salary employees.salary%TYPE;
BEGIN
SELECT salary
INTO v_salary
FROM employees
WHERE department_id = 10; -- Known to have multiple rows
EXCEPTION
WHEN TOO_MANY_ROWS THEN
-- Log error, pick a default, or re-raise custom exception
v_salary := 0; -- Fallback
log_error('Multiple salaries found for Dept 10');
WHEN NO_DATA_FOUND THEN
v_salary := NULL;
END;
Warning: Using WHEN TOO_MANY_ROWS to silently pick the "first" row (via a cursor loop alternative) hides data quality problems. Use this sparingly and with logging And that's really what it comes down to..
Advanced Handling: Explicit Cursors and Bulk Collect
For high-performance applications or complex logic, implicit SELECT INTO is often replaced by Explicit Cursors or BULK COLLECT It's one of those things that adds up. Practical, not theoretical..
Using Explicit Cursors for Control
An explicit cursor gives you granular control over fetching. You can open, fetch once, check for a second row, and close manually Not complicated — just consistent..
DECLARE
CURSOR c_emp IS
SELECT salary FROM employees WHERE department_id = 10;
v_sal employees.salary%TYPE;
v_dummy employees.salary%TYPE;
BEGIN
OPEN c_emp;
FETCH c_emp INTO v_sal; -- Fetch 1st row
IF c_emp%NOTFOUND THEN
-- Handle NO_DATA_FOUND
NULL;
ELSIF c_emp%FOUND THEN
-- Attempt to fetch 2nd row to check uniqueness
FETCH c_emp INTO v_dummy;
IF c_emp%FOUND THEN
-- Second row exists! Handle TOO_MANY_ROWS manually
RAISE_APPLICATION_ERROR(-20001, 'Multiple rows found');
END IF;
END IF;
CLOSE c_emp;
END;
Solution 6: Bulk Collect for Mass Processing
When the need arises to retrieve not just a single row, but an entire result set for further processing, the performance delta between row-by-row fetching and set-based collection becomes significant. BULK COLLECT minimizes context switches between the SQL and PL/SQL engines by loading multiple rows into collections in a single trip. This is particularly powerful when combined with FORALL for bulk DML operations.
DECLARE
TYPE t_salary IS TABLE OF employees.salary%TYPE;
l_salaries t_salary;
BEGIN
-- Fetch all salaries for dept 10 into a collection
SELECT salary
BULK COLLECT INTO l_salaries
FROM employees
WHERE department_id = 10;
-- Process or manipulate the collection as needed
FOR i IN 1..l_salaries.COUNT LOOP
-- Example: apply a raise, log, or compute statistics
NULL;
END LOOP;
END;
When to prefer BULK COLLECT over implicit SELECT INTO or explicit cursors:
- When expecting multiple rows and needing to process them all.
- When performance is critical and the dataset is