The employee ID is the primary key, so the lookup can only ever find one row. And yet SELECT ... INTO fails with ORA-01422: exact fetch returned more than the requested number of rows.
The cause: the parameter has the same name as the column. I reproduced it on Oracle AI Database 26ai Free (23.26.3) and ran the check and the fix. All output below is real SQL*Plus output.
Reproduce
Three employees, and a function that returns a name for an ID. The parameter is called emp_id, same as the column.
CREATE TABLE emp (emp_id NUMBER PRIMARY KEY, ename VARCHAR2(20)); INSERT INTO emp VALUES (101, 'Kim'); INSERT INTO emp VALUES (102, 'Lee'); INSERT INTO emp VALUES (103, 'Park'); COMMIT; CREATE OR REPLACE FUNCTION get_ename(emp_id IN NUMBER) RETURN VARCHAR2 IS v_name emp.ename%TYPE; BEGIN SELECT ename INTO v_name FROM emp WHERE emp_id = emp_id; RETURN v_name; END; / It compiles fine (Function created.). Now look up employee 102:
SELECT get_ename(102) FROM dual; SELECT get_ename(102) FROM dual * ERROR at line 1: ORA-01422: exact fetch returned more than the requested number of rows (0) There is exactly one employee 102, but Oracle says more than one row came back.
Check: read the source
SELECT line, text FROM user_source WHERE name = 'GET_ENAME' ORDER BY line; LINE TEXT ---------- ------------------------------------------------------------ 1 FUNCTION get_ename(emp_id IN NUMBER) RETURN VARCHAR2 IS 2 v_name emp.ename%TYPE; 3 BEGIN 4 SELECT ename INTO v_name FROM emp WHERE emp_id = emp_id; 5 RETURN v_name; 6 END; Line 4 is the problem. Inside a SQL statement, a name is resolved as a table column first. Both sides of emp_id = emp_id become the emp.emp_id column, which is true for every row. The parameter value 102 is never used, so all three rows land in the INTO.
Fix: rename the parameter
CREATE OR REPLACE FUNCTION get_ename(p_emp_id IN NUMBER) RETURN VARCHAR2 IS v_name emp.ename%TYPE; BEGIN SELECT ename INTO v_name FROM emp WHERE emp_id = p_emp_id; RETURN v_name; END; / Function created. SELECT get_ename(102) AS ename FROM dual; ENAME ---------- Lee Only employee 102, Lee, comes back.
Takeaways
- In SQL inside PL/SQL, when a column and a parameter share a name, the column wins
-
WHERE emp_id = emp_idis true for every row, soSELECT INTOgets many rows: ORA-01422 - It is not a compile error, so reading the code in
user_sourceis the fastest check - Prefixes like
p_for parameters andv_for variables prevent it
I keep the other ORA-01422 causes (lookup by a non-unique column like a name, history tables, 1:N joins, UNION ALL views, and more), each reproduced and fixed on a real database, here:
https://errorfixlab.96ssg.com/en/ora-01422/
This post was written with the help of generative AI, based on output actually run in a test environment.
