PL/SQL SELECT INTO π₯ΒΆ
Prerequisites: Oracle SELECT Statement, PL/SQL Variables
Mentor's Note: In regular SQL, you fetch data to see it on your screen. In PL/SQL, you fetch data to use it in your program.
SELECT INTOis the bridge that carries data from your tables into your variables. π‘
π The Scenario: The Targeted Pickup π¦ΒΆ
Imagine you are at a pizza shop. - The Database: The oven full of pizzas. - The SELECT INTO: You say "Give me the specific pizza with Order ID 101." - The Variable: You put that pizza in Your Box (Variable) so you can take it home and eat it. β
π» 1. The Basic SyntaxΒΆ
DECLARE
v_name VARCHAR2(100);
BEGIN
-- π Action: Pull one specific value
SELECT first_name INTO v_name
FROM employees
WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE('Fetched: ' || v_name);
END;
π 2. The Strict Rules (Architect's Note) π‘οΈΒΆ
SELECT INTO has two very strict rules. If you break them, your program will crash!
A. NO_DATA_FOUNDΒΆ
If your WHERE clause finds Zero rows, Oracle throws an error.
- Solution: Use an EXCEPTION block to handle this gracefully.
B. TOO_MANY_ROWSΒΆ
If your WHERE clause finds more than one row, Oracle throws an error.
- The Secret: SELECT INTO is designed for Exactly One row. If you need many rows, you must use a Cursor.
π» 3. Safe Implementation ExampleΒΆ
DECLARE
v_salary NUMBER;
BEGIN
SELECT salary INTO v_salary
FROM employees WHERE employee_id = 999; -- ID doesn't exist!
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('β οΈ Error: That employee was not found.');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('β οΈ Error: Multiple employees found.');
END;