Sub topic 10
Loading variables with SELECT INTO
This chapter assumes you can write basic SELECT statements and run anonymous blocks with SET SERVEROUTPUT ON. It also assumes you know how to declare a variable and assign to it with :=. The examples use the HR.EMPLOYEES table.
:= assigns a value you already have in PL/SQL. SELECT INTO assigns a value that lives in the database. It runs a query and copies the result into variables, so it is the usual way to bring table data into a block.
The basic form
SELECT INTO is a normal SELECT with an extra INTO clause between the select list and FROM.
SET SERVEROUTPUT ON
DECLARE
v_last_name VARCHAR2(25);
v_salary NUMBER(8,2);
BEGIN
SELECT last_name, salary
INTO v_last_name, v_salary
FROM employees
WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE(v_last_name || ' earns ' || v_salary);
END;
/Three rules apply:
- The
INTOlist matches the select list by position, not by name. The first column goes into the first variable, the second column into the second variable, and so on. - The number of variables must equal the number of selected columns. A mismatch is a compile-time error (PLS-00394), so the block never runs.
- Each variable's data type must be compatible with its column. PL/SQL converts implicitly where it can, but it raises an error if the value does not fit.
The statement can also have a WHERE, GROUP BY, ORDER BY, and any other clause a query allows. The only change from plain SQL is the INTO.
The exactly-one-row rule
SELECT INTO expects the query to return exactly one row. Any other row count raises an exception.
| Rows returned | Result |
|---|---|
| 0 | `NO_DATA_FOUND` is raised (ORA-01403) |
| 1 | The variables are loaded and execution continues |
| 2 or more | `TOO_MANY_ROWS` is raised (ORA-01422) |
Oracle fetches a second row to find out whether there is one. That is why the error for two rows is TOO_MANY_ROWS and not a silent truncation.
Handling the two exceptions
Put handlers in the EXCEPTION section of the block that contains the statement.
SET SERVEROUTPUT ON
DECLARE
v_last_name VARCHAR2(25);
BEGIN
SELECT last_name
INTO v_last_name
FROM employees
WHERE employee_id = -1;
DBMS_OUTPUT.PUT_LINE(v_last_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee with that ID.');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('More than one row matched.');
END;
/A handler ends the block. Control does not go back to the line after the failing SELECT. If you want to carry on with a default value, wrap the statement in its own nested block.
SET SERVEROUTPUT ON
DECLARE
v_last_name VARCHAR2(25);
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 inner handler sets a default and the inner block ends normally. The outer block then continues and prints Name: Unknown.
Do not read variables after an exception inside the same block. When SELECT INTO fails, the state of the INTO variables is not something to rely on.
Aggregates always return one row
A query with aggregate functions and no GROUP BY always returns exactly one row, even when no table rows match. That makes NO_DATA_FOUND impossible for such queries.
SET SERVEROUTPUT ON
DECLARE
v_count NUMBER;
v_avg NUMBER;
BEGIN
SELECT COUNT(*), AVG(salary)
INTO v_count, v_avg
FROM employees
WHERE department_id = -1;
DBMS_OUTPUT.PUT_LINE('Count: ' || v_count);
DBMS_OUTPUT.PUT_LINE('Average is null: ' ||
CASE WHEN v_avg IS NULL THEN 'yes' ELSE 'no' END);
END;
/COUNT(*) returns 0. AVG over zero rows returns NULL. No exception is raised. If you need to know whether any rows matched, test the count and not the exception.
NULL values are not "no data"
NO_DATA_FOUND means no row matched. A row that matched but holds a NULL loads that NULL into the variable.
SET SERVEROUTPUT ON
DECLARE
v_commission NUMBER(3,2);
BEGIN
SELECT commission_pct
INTO v_commission
FROM employees
WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE('Commission: ' || NVL(TO_CHAR(v_commission), 'none'));
END;
/Employee 100 has no commission, so the block prints Commission: none. Without NVL, the concatenation would silently print an empty string for the NULL, which is easy to misread.
Name collisions between variables and columns
Inside a SQL statement in a block, Oracle resolves a name to a column of the queried table before it considers a PL/SQL variable. If a variable has the same name as a column, the variable is hidden.
SET SERVEROUTPUT ON
DECLARE
employee_id NUMBER := 100;
v_last_name VARCHAR2(25);
BEGIN
SELECT last_name
INTO v_last_name
FROM employees
WHERE employee_id = employee_id;
DBMS_OUTPUT.PUT_LINE(v_last_name);
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Both names resolved to the column.');
END;
/Both employee_id references in the WHERE clause mean the column, so the condition is true for every non-null row. The query returns all rows and raises TOO_MANY_ROWS. Worse, in a DELETE or UPDATE the same mistake changes every row, and no exception warns you.
Two habits prevent this:
- Prefix variable names, for example
v_for variables,c_for constants, andp_for parameters. This tutorial usesv_andc_. - If you must keep a clashing name, qualify the variable with its block label, for example
<<main>>andmain.employee_id.
Type conversion and size errors
The target variable has to be able to hold the value. A too-small variable fails at run time, not at compile time.
SET SERVEROUTPUT ON
DECLARE
v_last_name VARCHAR2(3);
BEGIN
SELECT last_name
INTO v_last_name
FROM employees
WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE(v_last_name);
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Variable is too small for the value.');
END;
/The last name King has four characters and the variable holds three, so Oracle raises VALUE_ERROR (ORA-06502). A hard-coded VARCHAR2(25) can also go stale if someone widens the column later. The next chapter shows how %TYPE removes that risk by copying the column's type.
Selecting expressions and no table
The select list can hold any expression. When you need a value that does not come from a table, select from DUAL.
SET SERVEROUTPUT ON
DECLARE
v_today DATE;
v_next DATE;
BEGIN
SELECT SYSDATE, ADD_MONTHS(SYSDATE, 1)
INTO v_today, v_next
FROM dual;
DBMS_OUTPUT.PUT_LINE(TO_CHAR(v_today, 'YYYY-MM-DD') || ' -> ' ||
TO_CHAR(v_next, 'YYYY-MM-DD'));
END;
/In many cases you can write v_today := SYSDATE; instead and skip the query. Use SELECT INTO FROM dual when the expression is valid only in SQL.
When you want one row from many
Sometimes you really do want the top row from several. Restrict the result explicitly, and make the ordering deterministic.
SET SERVEROUTPUT ON
DECLARE
v_last_name VARCHAR2(25);
v_salary NUMBER(8,2);
BEGIN
SELECT last_name, salary
INTO v_last_name, v_salary
FROM employees
WHERE department_id = 50
ORDER BY salary DESC, employee_id
FETCH FIRST 1 ROW ONLY;
DBMS_OUTPUT.PUT_LINE(v_last_name || ': ' || v_salary);
END;
/FETCH FIRST 1 ROW ONLY needs Oracle Database 12c or later. On older versions, put the ordered query in an inline view and filter with ROWNUM = 1 outside it. Putting ROWNUM = 1 in the same WHERE as an ORDER BY picks a row before sorting, which gives the wrong answer.
The employee_id tie-breaker matters. If two employees share the top salary, the ordering without it is not guaranteed, and the result could change between runs.
Use this pattern only when "any one of these, by a defined rule" is what you mean. If a query should match exactly one row and a second row signals bad data, leave the query alone and let TOO_MANY_ROWS report the problem.
If you need to process every row, SELECT INTO is the wrong tool. Cursors and BULK COLLECT are built for that, and later chapters on them cover it.
Common mistakes
- Selecting the wrong number of columns for the
INTOlist. - Assuming a query that "always matches" will never raise
NO_DATA_FOUND. Data changes, and handling the exception is cheap. - Catching
TOO_MANY_ROWSand picking one row arbitrarily. That hides a data problem. - Naming a variable the same as a column.
- Using
WHEN OTHERS THEN NULLto avoid the two exceptions. This swallows every error, including ones you did not expect. - Reading a variable after the failed statement, in the same block, as if it had a meaningful value.
Exercises
Exercise
A block runs SELECT salary INTO vsalary FROM employees WHERE departmentid = 50. The department has many employees. What happens, and which exception section entry catches it?
Show answer
The query returns more than one row, so Oracle raises TOOMANYROWS (ORA-01422). A handler written as WHEN TOOMANYROWS THEN ... in the block's EXCEPTION section catches it. If there is no matching handler, the exception propagates to the caller.
Exercise
Write a block that loads the maximum salary of department 9999 (which does not exist) into vmax and prints it. Does it raise NODATA_FOUND? Explain.
Show answer
Use DECLARE vmax NUMBER; BEGIN SELECT MAX(salary) INTO vmax FROM employees WHERE departmentid = 9999; DBMSOUTPUT.PUTLINE(NVL(TOCHAR(vmax), 'no data')); END; with SET SERVEROUTPUT ON. It does not raise NODATAFOUND, because an aggregate query without GROUP BY always returns exactly one row. MAX over zero rows is NULL, so vmax is NULL and the block prints no data.
Exercise
A block declares a variable named lastname and runs SELECT lastname INTO lastname FROM employees WHERE employeeid = 100. Why is this risky, and how do you avoid the problem?
Show answer
Inside the SQL statement, lastname refers to the column, not the variable, so the name is ambiguous in intent. In a WHERE clause, a clash like WHERE lastname = lastname compares the column to itself and matches every row with a non-null value. Rename the variable with a prefix such as vlast_name, or qualify it with a block label.