Using MySQL's dept_stats(IN p_dept, OUT p_count, OUT p_total) from this topic, what do CALL dept_stats(20, @n, @t) and CALL dept_stats(40, @n, @t) leave in @n and @t?
Stored procedures and functions are named, precompiled programs kept in the database and run by the server. They add variables, IF/CASE, loops, cursors and exception handling to SQL, cutting network round trips and centralising business rules. MySQL and Oracle PL/SQL have them; SQLite does not.
A stored procedure is a named program written in the database's procedural extension of SQL — PL/SQL in Oracle, T-SQL in SQL Server, the SQL/PSM-based language in MySQL and DB2, PL/pgSQL in PostgreSQL — compiled and stored in the data dictionary and executed by the database server. A stored function is the same thing but returns a value. Together they are called stored routines or, with triggers and packages, stored programs.
A procedure body contains several statements, each ending with a semicolon. The mysql client would treat the first semicolon as the end of the CREATE PROCEDURE statement, so the delimiter is temporarily changed (to // or $$) and restored afterwards. Parameters are IN (passed in; the default), OUT (set by the procedure, read by the caller) or INOUT (both).
DELIMITER //
CREATE PROCEDURE dept_stats(IN p_dept INT, OUT p_count INT, OUT p_total DECIMAL(12,2))
BEGIN
SELECT COUNT(*), SUM(salary)
INTO p_count, p_total
FROM emp
WHERE dept_id = p_dept;
END //
DELIMITER ;
CALL dept_stats(20, @n, @t); -- @n, @t are session (user) variables
SELECT @n, @t; -- 4 | 180000.00
CALL dept_stats(40, @n, @t);
SELECT @n, @t; -- 0 | NULL (COUNT of no rows is 0, SUM is NULL)DELIMITER //
CREATE PROCEDURE add_bonus(INOUT p_amount DECIMAL(10,2), IN p_pct INT)
BEGIN
SET p_amount = p_amount + p_amount * p_pct / 100;
END //
CREATE PROCEDURE raise_salary(IN p_emp INT, IN p_pct DECIMAL(5,2))
BEGIN
DECLARE v_job VARCHAR(20);
SELECT job INTO v_job FROM emp WHERE emp_id = p_emp;
IF v_job = 'President' THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'President salary is fixed by the board';
ELSEIF p_pct > 20 THEN
SET p_pct = 20; -- cap any raise at 20 %
END IF;
UPDATE emp SET salary = salary * (1 + p_pct / 100) WHERE emp_id = p_emp;
END //
DELIMITER ;
SET @sal = 50000;
CALL add_bonus(@sal, 10);
SELECT @sal; -- 55000.00
CALL raise_salary(108, 10); -- Hari: 22000 → 24200
CALL raise_salary(101, 5); -- error 45000: President salary is fixed by the board
DROP PROCEDURE IF EXISTS add_bonus;Useful companions: SHOW PROCEDURE STATUS WHERE Db = 'hr'; lists procedures, SHOW CREATE PROCEDURE dept_stats; shows the source, and GRANT EXECUTE ON PROCEDURE hr.dept_stats TO clerk; lets a user run it without any privilege on emp.
CREATE PROCEDURE dept_count @dept INT AS SELECT COUNT(*) FROM emp WHERE dept_id = @dept; GO and EXEC dept_count 20;. Oracle: CREATE OR REPLACE PROCEDURE … IS … BEGIN … END; and EXEC raise_salary(108, 10) in SQL*Plus.| Construct | MySQL | Oracle PL/SQL |
|---|---|---|
| Declare a variable | DECLARE v_total INT DEFAULT 0; | v_total NUMBER := 0; (in DECLARE section) |
| Assign | SET v_total = v_total + 1; or SELECT … INTO v_total | v_total := v_total + 1; or SELECT … INTO v_total |
| Type of a column | — | v_sal emp.salary%TYPE; / whole row r emp%ROWTYPE; |
| If | IF … THEN … ELSEIF … ELSE … END IF; | IF … THEN … ELSIF … ELSE … END IF; |
| Case | CASE WHEN … THEN … ELSE … END CASE; | CASE WHEN … THEN … ELSE … END CASE; |
| Pre-test loop | WHILE cond DO … END WHILE; | WHILE cond LOOP … END LOOP; |
| Post-test loop | REPEAT … UNTIL cond END REPEAT; | LOOP … EXIT WHEN cond; END LOOP; |
| Counting loop | — (use WHILE) | FOR i IN 1..10 LOOP … END LOOP; |
| Leave / skip | LEAVE label; / ITERATE label; | EXIT; / CONTINUE; |
SELECT 'text'; | DBMS_OUTPUT.PUT_LINE('text'); after SET SERVEROUTPUT ON |
-- MySQL
DELIMITER //
CREATE PROCEDURE sum_to(IN n INT, OUT total INT)
BEGIN
DECLARE i INT DEFAULT 1;
SET total = 0;
WHILE i <= n DO
SET total = total + i;
SET i = i + 1;
END WHILE;
END //
DELIMITER ;
CALL sum_to(10, @s); SELECT @s; -- 55
-- Oracle PL/SQL anonymous block
DECLARE
v_total NUMBER := 0;
BEGIN
FOR i IN 1..10 LOOP
v_total := v_total + i;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Sum = ' || v_total); -- Sum = 55
END;
/SQL*Plus a line containing only / sends the block to the server.SET SERVEROUTPUT ON
DECLARE
v_name emp.ename%TYPE; -- same type as the column
v_sal emp.salary%TYPE;
BEGIN
SELECT ename, salary INTO v_name, v_sal FROM emp WHERE emp_id = 104;
DBMS_OUTPUT.PUT_LINE(v_name || ' earns ' || v_sal); -- Divya earns 50000
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No such employee');
END;
/CREATE OR REPLACE PROCEDURE raise_salary (
p_emp_id IN emp.emp_id%TYPE,
p_pct IN NUMBER DEFAULT 10,
p_new OUT emp.salary%TYPE
) IS
BEGIN
UPDATE emp SET salary = salary * (1 + p_pct / 100)
WHERE emp_id = p_emp_id
RETURNING salary INTO p_new;
IF SQL%ROWCOUNT = 0 THEN
RAISE_APPLICATION_ERROR(-20010, 'Employee ' || p_emp_id || ' not found');
END IF;
END raise_salary;
/
-- SQL*Plus
VARIABLE v NUMBER
EXEC raise_salary(108, 10, :v)
PRINT v -- 24200
-- from another block: raise_salary(p_emp_id => 108, p_new => v_out); (named notation)Anonymous blocks are compiled each time they run and are not stored; named procedures, functions, packages and triggers are compiled once and stored. In parameters are read-only inside the procedure, OUT parameters start as NULL and are copied back on success, and IN OUT parameters carry a value in and out. EXEC proc(args) is SQL*Plus shorthand for BEGIN proc(args); END;.
A function declares a return type and must execute a RETURN statement with a value of that type. Because it returns a value it can be used wherever an expression is allowed — in SELECT lists, WHERE clauses and other routines. Functions called from SQL should not modify data (Oracle raises ORA-14551 if a function invoked from a query performs DML, and MySQL forbids statements that commit).
-- MySQL: annual pay = 12 months + one month's bonus for salaries of 50000 and above
DELIMITER //
CREATE FUNCTION annual_pay(p_salary DECIMAL(10,2)) RETURNS DECIMAL(12,2)
DETERMINISTIC
BEGIN
DECLARE v_bonus DECIMAL(10,2) DEFAULT 0;
IF p_salary >= 50000 THEN
SET v_bonus = p_salary;
END IF;
RETURN 12 * p_salary + v_bonus;
END //
DELIMITER ;
SELECT ename, annual_pay(salary) FROM emp WHERE dept_id = 10;
-- Anil 1170000.00 (12 × 90000 + 90000)
-- Hari 264000.00 (12 × 22000, no bonus)
-- Oracle
CREATE OR REPLACE FUNCTION get_salary (p_emp_id IN NUMBER) RETURN NUMBER IS
v_sal emp.salary%TYPE;
BEGIN
SELECT salary INTO v_sal FROM emp WHERE emp_id = p_emp_id;
RETURN v_sal;
EXCEPTION
WHEN NO_DATA_FOUND THEN RETURN -1;
END;
/
SELECT get_salary(105) FROM dual; -- 50000
SELECT get_salary(999) FROM dual; -- -1MySQL asks every function to declare its nature — DETERMINISTIC (same inputs always give the same output), NO SQL, READS SQL DATA or MODIFIES SQL DATA — and with binary logging enabled refuses to create a function that declares none of DETERMINISTIC, NO SQL or READS SQL DATA unless the server option log_bin_trust_function_creators is set.
SQL works on sets, but procedural code handles one value at a time. A cursor bridges the gap: it is a named pointer into the result set of a query that lets the program fetch and process rows one by one. Every SQL statement executed in PL/SQL uses an implicit cursor (named SQL); for multi-row queries you declare an explicit cursor.
DECLARE
CURSOR c_dept20 IS
SELECT ename, salary FROM emp WHERE dept_id = 20 ORDER BY emp_id;
v_name emp.ename%TYPE;
v_sal emp.salary%TYPE;
BEGIN
OPEN c_dept20;
LOOP
FETCH c_dept20 INTO v_name, v_sal;
EXIT WHEN c_dept20%NOTFOUND; -- test right after FETCH
DBMS_OUTPUT.PUT_LINE(c_dept20%ROWCOUNT || '. ' || v_name || ' ' || v_sal);
END LOOP;
DBMS_OUTPUT.PUT_LINE('Rows fetched: ' || c_dept20%ROWCOUNT);
CLOSE c_dept20;
END;
/
-- 1. Bindu 60000 2. Divya 50000 3. Eby 50000 4. Indu 20000 Rows fetched: 4
BEGIN
FOR r IN (SELECT ename, salary FROM emp WHERE dept_id = 20 ORDER BY emp_id) LOOP
DBMS_OUTPUT.PUT_LINE(r.ename || ' ' || r.salary); -- opens, fetches, closes for you
END LOOP;
END;
/| Moment (dept 20 cursor, 4 rows) | %ISOPEN | %FOUND | %NOTFOUND | %ROWCOUNT |
|---|---|---|---|---|
| Before OPEN | FALSE | INVALID_CURSOR error | INVALID_CURSOR error | INVALID_CURSOR error |
| After OPEN, before any FETCH | TRUE | NULL | NULL | 0 |
| After 1st FETCH (Bindu) | TRUE | TRUE | FALSE | 1 |
| After 4th FETCH (Indu) | TRUE | TRUE | FALSE | 4 |
| After 5th FETCH (no row) | TRUE | FALSE | TRUE | 4 |
| After CLOSE | FALSE | INVALID_CURSOR error | INVALID_CURSOR error | INVALID_CURSOR error |
For the implicit cursor, SQL%ROWCOUNT after UPDATE emp SET salary = salary + 1000 WHERE dept_id = 30 is 3, SQL%FOUND is TRUE, and SQL%ISOPEN is always FALSE because Oracle closes implicit cursors automatically. Cursors can take parameters (CURSOR c(p_dept NUMBER) IS … WHERE dept_id = p_dept; then OPEN c(30);), and FOR UPDATE with WHERE CURRENT OF c updates the row the cursor is on.
DELIMITER //
CREATE PROCEDURE list_dept(IN p_dept INT)
BEGIN
DECLARE v_name VARCHAR(30);
DECLARE v_sal DECIMAL(10,2);
DECLARE done INT DEFAULT 0;
DECLARE c CURSOR FOR
SELECT ename, salary FROM emp WHERE dept_id = p_dept ORDER BY emp_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; -- fires when FETCH finds no row
OPEN c;
read_loop: LOOP
FETCH c INTO v_name, v_sal;
IF done = 1 THEN
LEAVE read_loop;
END IF;
SELECT CONCAT(v_name, ' earns ', v_sal) AS line;
END LOOP;
CLOSE c;
END //
DELIMITER ;
CALL list_dept(30); -- Charles earns 55000.00 / Fathima earns 30000.00 / Gopal earns 28000.00| Predefined exception (Oracle) | Error | Raised when |
|---|---|---|
| NO_DATA_FOUND | ORA-01403 | SELECT … INTO returns no row |
| TOO_MANY_ROWS | ORA-01422 | SELECT … INTO returns more than one row |
| ZERO_DIVIDE | ORA-01476 | Division by zero |
| DUP_VAL_ON_INDEX | ORA-00001 | INSERT/UPDATE violates a unique index |
| VALUE_ERROR | ORA-06502 | Conversion, truncation or size error |
| INVALID_NUMBER | ORA-01722 | String-to-number conversion fails in SQL |
| INVALID_CURSOR | ORA-01001 | Illegal cursor operation, e.g. FETCH from a closed cursor |
| CURSOR_ALREADY_OPEN | ORA-06511 | OPEN on a cursor that is already open |
DECLARE
e_low_budget EXCEPTION; -- user-defined
v_budget project.budget%TYPE;
BEGIN
SELECT budget INTO v_budget FROM project WHERE proj_id = 4;
IF v_budget < 350000 THEN
RAISE e_low_budget;
END IF;
DBMS_OUTPUT.PUT_LINE('Budget OK');
EXCEPTION
WHEN e_low_budget THEN
DBMS_OUTPUT.PUT_LINE('Budget too low: ' || v_budget); -- Budget too low: 300000
WHEN OTHERS THEN -- catch-all, always last
DBMS_OUTPUT.PUT_LINE('Error ' || SQLCODE || ': ' || SQLERRM);
END;
/When an exception is raised, the rest of the executable section is skipped and the first matching handler runs; if the block has no matching handler the exception propagates to the enclosing block or the caller. RAISE_APPLICATION_ERROR(code, message) raises an error with a programmer-chosen code between −20000 and −20999 that client programs can catch. MySQL's equivalents are DECLARE CONTINUE | EXIT HANDLER FOR SQLEXCEPTION | NOT FOUND | SQLSTATE '…' and SIGNAL / RESIGNAL.
An Oracle package groups related procedures, functions, types, variables and cursors. The specification declares the public interface; the body contains the implementation and any private helpers. Packages give encapsulation, overloading (two procedures with the same name but different parameters), session-wide state in package variables, and better performance because the whole package is loaded into memory on first use.
CREATE OR REPLACE PACKAGE hr_pkg AS
PROCEDURE raise_salary(p_emp_id NUMBER, p_pct NUMBER);
FUNCTION get_salary(p_emp_id NUMBER) RETURN NUMBER;
END hr_pkg;
/
CREATE OR REPLACE PACKAGE BODY hr_pkg AS
PROCEDURE raise_salary(p_emp_id NUMBER, p_pct NUMBER) IS
BEGIN
UPDATE emp SET salary = salary * (1 + p_pct / 100) WHERE emp_id = p_emp_id;
END;
FUNCTION get_salary(p_emp_id NUMBER) RETURN NUMBER IS
v NUMBER;
BEGIN
SELECT salary INTO v FROM emp WHERE emp_id = p_emp_id;
RETURN v;
END;
END hr_pkg;
/
EXEC hr_pkg.raise_salary(108, 5)| Procedure | Function | Trigger | |
|---|---|---|---|
| Invoked by | Explicit call: CALL / EXEC / from code | Explicit call, often inside SQL | Implicitly, by an event (INSERT, UPDATE, DELETE …) |
| Return value | None (OUT / INOUT parameters instead) | Exactly one, via RETURN | None |
| Parameters | IN, OUT, INOUT | Usually IN only | None (OLD/NEW instead) |
| Usable in SELECT | No | Yes | No |
| DML inside | Yes | Avoid (not allowed when called from a query) | Yes |
| COMMIT / ROLLBACK inside | Allowed | Not when called from SQL | Normally not allowed |
| Typical use | Business operations, batch jobs | Computations, derived values | Auditing, enforcing rules automatically |
Try the problem first, then reveal the working one step at a time.
Using MySQL's dept_stats(IN p_dept, OUT p_count, OUT p_total) from this topic, what do CALL dept_stats(20, @n, @t) and CALL dept_stats(40, @n, @t) leave in @n and @t?
Trace the PL/SQL block that opens c_dept20 (SELECT ename, salary FROM emp WHERE dept_id = 20 ORDER BY emp_id), fetches in a LOOP with EXIT WHEN c_dept20%NOTFOUND, prints %ROWCOUNT with each name, and prints %ROWCOUNT again after the loop.
In PL/SQL, what happens when each statement runs inside a block with no handler, and then with a handler WHEN NO_DATA_FOUND THEN … WHEN TOO_MANY_ROWS THEN …? (a) SELECT salary INTO v FROM emp WHERE emp_id = 105; (b) … WHERE dept_id = 30; (c) … WHERE dept_id = 40.
Choose the right stored program: (a) compute a person's income-tax slab inside a report query; (b) every night, close all expired allotments and e-mail a summary table to accounts; (c) record every change to an allottee's address automatically, whichever application makes it.
Write a MySQL function annual_pay(p_salary) that returns 12 × salary plus a one-month bonus when the salary is at least 50000. What does it return for Bindu (60000) and Gopal (28000)?
A cursor over department 30 ordered by emp_id (3 rows) is opened, fetched four times and then closed. Give %ROWCOUNT and %NOTFOUND after the 2nd fetch and after the 4th fetch. What happens if %ROWCOUNT is referenced after CLOSE?
Rewrite this explicit-cursor loop as a cursor FOR loop: OPEN c; LOOP FETCH c INTO v_name, v_sal; EXIT WHEN c%NOTFOUND; DBMS_OUTPUT.PUT_LINE(v_name); END LOOP; CLOSE c; — where c is SELECT ename, salary FROM emp WHERE job = 'Clerk'.
Find and fix the errors: (a) a MySQL procedure typed straight into the mysql client without changing the delimiter; (b) a PL/SQL IF that uses ELSEIF; (c) a MySQL procedure that declares its CONTINUE HANDLER before its cursor.
Write an Oracle procedure transfer_budget(p_from, p_to, p_amount) that moves budget between two projects, refuses to leave the source below zero, and commits only if both updates succeed.
SQL*Plus) and returns values only through OUT/INOUT parameters.10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.