Database systems · Chapter 5 · Section 5.8 · Beginner guide

Stored procedures in plain terms

A stored procedure is a small program that lives inside the database. You give it a name once, and after that anyone can run it with one line. This page starts with three simpler stored objects you have already met (a view, a trigger, and a function), then takes a procedure apart piece by piece, first without a cursor and then with one. Every example is MySQL, the database on our lab PCs.

The tables we use

Everything on this page runs against two small tables, the same DEPARTMENT and EMPLOYEES tables used on the join, aggregate, and subquery example pages.

The columns that matter here.
TableColumns
DEPARTMENTdept_id, dept_name, location
EMPLOYEESemp_id, first_name, last_name, hire_date, salary, dept_id

A few examples also write to a small log table. Create it once before you try them:

CREATE TABLE SALARY_AUDIT (
    audit_id    INT AUTO_INCREMENT PRIMARY KEY,
    dept_id     INT,
    pct         DECIMAL(5,2),
    emp_count   INT,
    changed_at  DATETIME
);

Warm up, part 1

A view: a saved query you treat like a table

A view stores a SELECT statement under a name. It holds no data of its own; every time you use it, MySQL runs the saved query.

-- save a join once, under a simple name
CREATE VIEW emp_directory AS
SELECT E.first_name, E.last_name, D.dept_name, D.location
FROM   EMPLOYEES E
       JOIN DEPARTMENT D ON E.dept_id = D.dept_id;

-- now anyone can query it as if it were a table
SELECT * FROM emp_directory WHERE location = 'Turlock';

How it starts: you name it in the FROM clause of a query.

When to use one: when you have a long join, or a query people run often, and you want to save it so other people can query it by a simple name without retyping the join.

Warm up, part 2

A trigger: code that runs by itself when a table changes

A trigger is attached to one table and tied to an INSERT, UPDATE, or DELETE on it. Nobody calls it. The DBMS runs it automatically every time that change happens.

-- give EMPLOYEES a column to hold the time a row was added
ALTER TABLE EMPLOYEES ADD created_at DATETIME;

-- before any new row goes in, stamp the current time on it
CREATE TRIGGER trg_emp_stamp
BEFORE INSERT ON EMPLOYEES
FOR EACH ROW
SET NEW.created_at = NOW();

-- test it: we never mention created_at, but it gets filled in
INSERT INTO EMPLOYEES (emp_id, first_name, last_name, salary, dept_id)
VALUES (125, 'Rosa', 'Lopez', 60000, 3);

SELECT emp_id, last_name, created_at FROM EMPLOYEES WHERE emp_id = 125;

NEW means "the row that is about to be inserted." Setting NEW.created_at changes that row before it is saved.

How it starts: the DBMS runs it by itself when the table is changed.

When to use one: when something must happen every single time, no matter who makes the change or which program they use, such as stamping the time on every inserted row or writing an audit record.

Warm up, part 3

A function: code that works out one value

A stored function takes some input, works out exactly one value, and hands it back. Because it returns a value, you can drop it right into a SELECT, just like the built in ROUND or UPPER.

-- how many full years since an employee was hired
CREATE FUNCTION years_of_service(p_hire DATE)
RETURNS INT
NO SQL
RETURN TIMESTAMPDIFF(YEAR, p_hire, CURDATE());

-- use it in a SELECT list, once per row
SELECT first_name, last_name, years_of_service(hire_date) AS years
FROM   EMPLOYEES
ORDER BY years DESC;

How it starts: you write it into an expression, such as a SELECT list or a WHERE clause.

When to use one: when you need to work out one value, such as one employee's years of service, and use it inside a query.

The view, trigger, and function above are each a single statement, so they need no BEGIN, no END, and no DELIMITER. Stored procedures usually hold many statements, which is where those come in.

Putting them side by side

Which one do I use?

All four are stored in the database. What separates them is how each one gets started and what kind of job it does.

Four kinds of stored object.
ObjectWhat it isHow it starts
ViewA stored query used in place of a table nameNamed in the FROM clause of a query
TriggerStored code attached to a table, tied to an insert, update, or deleteThe DBMS runs it by itself when the table changes
FunctionStored code that works out one value and hands it backWritten into an expression, such as a SELECT list
Stored procedureStored code that runs on request and may change dataSomething calls it by name with CALL

Match the job to the object

Read the job, then ask: does it return one value, must it happen automatically, is it just a saved query, or is it a task with several steps?
Best choiceThe jobThe clue
Stored procedureGive every employee in a department a raise, then write an audit rowSeveral steps, changes data, someone asks for it
FunctionWork out one employee's years of service for use in a SELECT listOne value, used inside a query
TriggerStamp the time on any row inserted into a table, no matter who inserts it"Any row" and "no matter who" mean automatic
ViewSave a long join so other people can query it by a simple nameIt is only a query, with no steps or changes

The first job in that table, the department raise, is the procedure we build in the rest of this page.

Section 5.8

Why stored procedures are used

Without a procedure, an application program has to send each SQL statement to the server one at a time. With a procedure, the statements already live on the server, and the program sends one short CALL.

Without a procedure: the app sends all of this

SELECT COUNT(*) FROM EMPLOYEES
 WHERE dept_id = 3;
UPDATE EMPLOYEES
   SET salary = salary * 1.05
 WHERE dept_id = 3;
INSERT INTO SALARY_AUDIT
  (dept_id, pct, emp_count, changed_at)
VALUES (3, 5, 6, NOW());

With a procedure: the app sends this

CALL dept_raise(3, 5, @n);

Less network traffic

One call replaces a long stream of individual statements traveling between the program and the server.

Better performance

The code runs on the server, right next to the data, so nothing has to be shipped back and forth between steps.

Code sharing

The website, the payroll app, and a staff member at the MySQL prompt all use the one copy stored in the database.

Less duplicated code

The rule is written once. It does not have to be rewritten in every program, where the copies could slowly drift apart.

Part 1

The parts of a stored procedure, without a cursor

Here is the whole department raise procedure first. Read it top to bottom once, then we will go through it one piece at a time.

DELIMITER $$                                    -- 1. change the end marker

CREATE PROCEDURE dept_raise(                    -- 2. the header
    IN  p_dept  INT,                            -- 3. parameters
    IN  p_pct   DECIMAL(5,2),
    OUT p_count INT
)
BEGIN                                           -- 4. the body starts
    DECLARE v_count INT DEFAULT 0;              -- 5. local variable

    SELECT COUNT(*) INTO v_count                -- 6. store a query result
    FROM   EMPLOYEES
    WHERE  dept_id = p_dept;

    IF v_count = 0 THEN                         -- 7. make a decision
        SELECT 'No employees in that department' AS message;
        SET p_count = 0;
    ELSEIF p_pct > 20 THEN
        SELECT 'Raise is too large, nothing changed' AS message;
        SET p_count = 0;
    ELSE
        UPDATE EMPLOYEES                        -- 8. do the real work
        SET    salary = salary * (1 + p_pct / 100)
        WHERE  dept_id = p_dept;

        INSERT INTO SALARY_AUDIT (dept_id, pct, emp_count, changed_at)
        VALUES (p_dept, p_pct, v_count, NOW());

        SET p_count = v_count;                  -- 9. send a value back
    END IF;
END $$                                          -- 10. the body ends

DELIMITER ;                                     -- 11. put the marker back

CALL dept_raise(3, 5, @how_many);               -- 12. run it
SELECT @how_many;                               -- 13. read the OUT value

1 and 11. DELIMITER

Every statement inside the body ends with a semicolon. Normally the semicolon tells the mysql client "this statement is finished, send it." That would send the procedure after its first line, cut in half. DELIMITER $$ tells the client to treat $$ as the end marker for a while, so the whole procedure goes over as one statement. DELIMITER ; puts things back to normal.

The server never sees DELIMITER. It is an instruction to the client program only. In VS Code with SQLTools, leave both DELIMITER lines out, change END $$ to END;, highlight the whole CREATE PROCEDURE statement, and run the selection. See the Chapter 5 review for more on this.

2. The header

Reading CREATE PROCEDURE dept_raise( ... )
CREATE PROCEDUREThe statement that defines a new routine and saves it in the database
dept_raiseThe name you will use to call it
( )Holds the parameter list. The parentheses are still required when there are no parameters: CREATE PROCEDURE list_all()

3. Parameters

Each parameter has three parts: a mode, a name, and a data type. In IN p_dept INT, the mode is IN, the name is p_dept, and the type is INT.

The three modes.
INCarries a value into the procedure. If you write no mode at all, MySQL treats it as IN.
OUTSends a value back out to whoever made the call.
INOUTCarries a value in, and sends a changed value back.

Never name a parameter the same as a column. If the parameter were called dept_id, then WHERE dept_id = dept_id would compare it to itself, be true for every row, and give the whole company a raise. That is why this page starts parameter names with p_ and local variables with v_.

4 and 10. BEGIN and END

Everything between BEGIN and END is the body, the statements that run each time the procedure is called. They run in order, top to bottom.

5. DECLARE a local variable

DECLARE v_count INT DEFAULT 0; makes a variable named v_count that holds whole numbers and starts at 0. DEFAULT sets the starting value on the same line; leave it off and the variable starts as NULL.

A local variable exists only while the body is running. When the procedure finishes, it is gone. All DECLARE statements must come first, right after BEGIN, before any other statement.

6. SELECT ... INTO

A normal SELECT shows you rows. Adding INTO v_count keeps the answer inside the procedure instead, by storing it in a variable. The query must return exactly one row for this to work.

7. IF, ELSEIF, ELSE, END IF

A branch picks which statements run.
IF ... THENOpens the branch with the first condition to test
ELSEIF ... THENAnother condition, tested only when the ones before it were false
ELSECatches everything none of the conditions matched
END IF;Closes the branch

Notice that MySQL writes ELSEIF as one word.

8. The real work

Any ordinary SQL can go in the body: UPDATE, INSERT, DELETE, SELECT. Here an UPDATE gives the raise and an INSERT writes the audit row. A SELECT with no INTO, like the message lines, sends its rows straight back to the caller as a result, the same as running it by hand.

9. SET

SET gives a new value to a variable or parameter that already exists. SET p_count = v_count; copies the count into the OUT parameter so the caller can see it.

12 and 13. CALL and the session variable

CALL dept_raise(3, 5, @how_many);
SELECT @how_many;

The values you hand over in the CALL, here 3 and 5, are the arguments. The names in the header, p_dept and p_pct, are the parameters. An argument fills a parameter for that one call only.

For the OUT parameter you pass a session variable, a name that starts with @. You do not have to declare it. The procedure fills it in, and it lasts until you close your connection, so you can read it afterward with SELECT @how_many;.

Variables, parameters, and procedures: how long each one lasts

Lifetime and scope.
Parameter valueOnly for the one call that supplied it
Local variable (DECLARE)Only while the block it was declared in is running
Session variable (@name)Until the connection is closed
The stored procedureUntil somebody drops it, even after you disconnect or restart

One more building block: a WHILE loop

The raise procedure did not need to repeat anything, but procedures often do. A WHILE loop tests its condition before each pass and keeps going while it is true.

DELIMITER $$
CREATE PROCEDURE count_to(IN p_max INT)
BEGIN
    DECLARE i      INT DEFAULT 1;
    DECLARE v_list VARCHAR(200) DEFAULT '';

    WHILE i <= p_max DO                 -- test first, then run the body
        SET v_list = CONCAT(v_list, i, ' ');
        SET i = i + 1;                  -- without this the loop never ends
    END WHILE;

    SELECT v_list AS numbers;
END $$
DELIMITER ;

CALL count_to(5);                       -- numbers: 1 2 3 4 5

MySQL has two other loops. REPEAT ... UNTIL condition END REPEAT; tests at the bottom, so its body always runs at least once. LOOP ... END LOOP; has no condition at all and runs until a LEAVE statement jumps out of it. You will see LOOP and LEAVE in the cursor example next.

Part 2

The parts of a stored procedure, with a cursor

SELECT ... INTO only works when the query returns one row. When you need to look at many rows and handle each one separately, you use a cursor.

Think of a cursor as a finger moving down the rows of a query result. It points at one row at a time, you read that row into variables, do something with it, then move the finger to the next row.

New job: in one department, employees earning under $70,000 get a 6 percent raise and everyone else gets 3 percent. Each row needs its own decision, so we walk the rows with a cursor.

DELIMITER $$
CREATE PROCEDURE tiered_raise(IN p_dept INT)
BEGIN
    -- A. variables (always first)
    DECLARE v_done   INT DEFAULT 0;
    DECLARE v_id     INT;
    DECLARE v_salary DECIMAL(10,2);
    DECLARE v_count  INT DEFAULT 0;

    -- B. the cursor and the query it will walk
    DECLARE emp_cursor CURSOR FOR
        SELECT emp_id, salary
        FROM   EMPLOYEES
        WHERE  dept_id = p_dept;

    -- C. the handler: what to do when the rows run out
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = 1;

    -- D. run the query and get ready to read
    OPEN emp_cursor;

    read_loop: LOOP
        -- E. read the next row into variables
        FETCH emp_cursor INTO v_id, v_salary;

        -- F. stop when there are no more rows
        IF v_done = 1 THEN
            LEAVE read_loop;
        END IF;

        -- G. handle this one row
        IF v_salary < 70000 THEN
            UPDATE EMPLOYEES SET salary = salary * 1.06 WHERE emp_id = v_id;
        ELSE
            UPDATE EMPLOYEES SET salary = salary * 1.03 WHERE emp_id = v_id;
        END IF;

        SET v_count = v_count + 1;
    END LOOP;

    -- H. finished with the cursor
    CLOSE emp_cursor;

    SELECT v_count AS employees_updated;
END $$
DELIMITER ;

CALL tiered_raise(3);

What is new compared with Part 1

The cursor lifecycle, plus the two pieces that make it work.
DECLARE ... CURSOR FORNames the cursor and gives it the query whose rows it will walk. Nothing runs yet.
DECLARE CONTINUE HANDLER FOR NOT FOUNDWhen a FETCH finds no more rows, MySQL raises a condition called NOT FOUND. This handler catches it, sets v_done = 1, and lets the procedure carry on running instead of stopping with an error.
OPENRuns the query and puts the finger just above the first row.
FETCH ... INTOCopies the next row into local variables and moves the finger down one row. The variables must be listed in the same order as the columns in the cursor's SELECT.
LOOP and LEAVEread_loop: is a label, a name for the loop. LEAVE read_loop; jumps out of it. Check v_done right after FETCH, before using the variables, or the last row gets processed twice.
CLOSEFinishes with the cursor and releases it.

Order matters in the declarations. MySQL insists on this order right after BEGIN: variables, then cursors, then handlers. Put a variable after the cursor, or any DECLARE after an ordinary statement, and you get a syntax error.

The four sections of any procedure

Every procedure on this page fits this outline.
Parameter listThe values the procedure expects, with their modes and types, in the header
Declaration sectionDECLARE statements for variables and cursors, which must come before anything else
Handler declarationsWhat to do when a condition such as NOT FOUND arises (the last of the declarations)
Executable sectionThe SQL and the IF, WHILE, and LOOP statements that do the actual work

CONTINUE versus EXIT handlers

A CONTINUE handler deals with the condition and lets the procedure keep running, which is what a cursor loop needs. An EXIT handler deals with the condition and then leaves the BEGIN ... END block. Besides NOT FOUND, the other condition you will see most is SQLEXCEPTION, raised when a statement fails with an error.

Use a cursor last, not first. This job could also be done with one UPDATE and a CASE expression, which is faster. A cursor earns its place when each row needs several steps or a decision that is hard to write in a single statement. In an intro course its main value is showing you how a program can walk through a result one row at a time.

Housekeeping

Listing, viewing, and removing procedures

-- list the procedures in the current database
SHOW PROCEDURE STATUS WHERE Db = DATABASE();

-- print one procedure back exactly as it was written
SHOW CREATE PROCEDURE dept_raise;

-- the same list as a normal query on the data dictionary
SELECT routine_name, routine_type
FROM   information_schema.routines
WHERE  routine_schema = DATABASE();

-- remove one, with no error if it is not there
DROP PROCEDURE IF EXISTS dept_raise;

To change the body of a procedure, drop it and create it again. ALTER PROCEDURE exists, but it can only change settings such as the comment, never the code.

The big picture

Sequence, selection, iteration, and modularity

Plain SQL describes a result, but it cannot make decisions or repeat steps. Stored procedures add the four ideas of structured programming, the same ones you see in Python or any other language. Here is each one on its own.

Sequence: statements run one after another

CREATE PROCEDURE show_counts()
BEGIN
    SELECT COUNT(*) AS departments FROM DEPARTMENT;   -- runs first
    SELECT COUNT(*) AS employees   FROM EMPLOYEES;    -- runs second
END;

Selection: IF and ELSEIF choose which statements run

CREATE PROCEDURE pay_band(IN p_salary DECIMAL(10,2))
BEGIN
    IF p_salary >= 100000 THEN
        SELECT 'High' AS band;
    ELSEIF p_salary >= 70000 THEN
        SELECT 'Middle' AS band;
    ELSE
        SELECT 'Starting' AS band;
    END IF;
END;

CALL pay_band(82000);       -- band: Middle

Iteration: WHILE, REPEAT, and LOOP run statements more than once

CREATE PROCEDURE countdown(IN p_start INT)
BEGIN
    DECLARE v_text VARCHAR(100) DEFAULT '';
    WHILE p_start > 0 DO
        SET v_text  = CONCAT(v_text, p_start, ' ');
        SET p_start = p_start - 1;
    END WHILE;
    SELECT CONCAT(v_text, 'liftoff') AS countdown;
END;

CALL countdown(3);          -- countdown: 3 2 1 liftoff

Modularity: a named routine called from many places

Once dept_raise exists, other procedures (and every application) can call it instead of rewriting it. This one reuses it for two departments:

CREATE PROCEDURE year_end_raises()
BEGIN
    CALL dept_raise(2, 4, @eng);     -- Engineering gets 4 percent
    CALL dept_raise(3, 5, @sales);   -- Sales gets 5 percent
    SELECT @eng AS engineering_updated, @sales AS sales_updated;
END;

CALL year_end_raises();

These four are written the VS Code way, with no DELIMITER and a plain END;. At the mysql> prompt, wrap each one in DELIMITER $$ ... END $$ ... DELIMITER ; as in the earlier examples.

Quick check

If you remember only these

  • A view is a saved query, a trigger runs by itself when a table changes, a function returns one value inside a query, and a procedure is a task you run with CALL.
  • Procedures cut network traffic, run next to the data, and keep one shared copy of a rule instead of many.
  • Parameters have a mode (IN, OUT, INOUT), a name, and a type. No mode means IN.
  • DECLARE comes first in the body. Order: variables, cursors, handlers.
  • SET assigns a value; SELECT ... INTO stores one query result in a variable.
  • A cursor goes DECLARE, OPEN, FETCH (in a loop), CLOSE, with a NOT FOUND handler to end the loop.
  • DELIMITER is for the mysql client only. Leave it out in VS Code.

Common errors and what they mean:

Four mistakes almost everyone makes once.
Too few arguments in a CALLMySQL refuses the call and tells you how many arguments it expected.
A DECLARE after another statementSyntax error. Declarations have to come first in the block.
A plain SELECT inside a functionError: a function is not allowed to return a result set. Use SELECT ... INTO and RETURN instead.
A procedure name in a SELECT listError: no function of that name exists. Procedures are run with CALL, not inside a query.