Chapter 15: Stored Procedures & Functions

Now we’ll learn how to save reusable code inside the database itself — like writing your own mini-programs!

We have two main concepts today:

  • Stored Procedures → Like mini-programs that can do multiple things (INSERT, UPDATE, SELECT, etc.)
  • User-Defined Functions (UDFs) → Return a single value (like built-in functions: CONCAT, NOW, etc.)

Let’s start with Stored Procedures — they’re the most commonly used.

1. What is a Stored Procedure?

A stored procedure is a saved block of SQL code that:

  • Has a name
  • Can accept parameters (like function arguments)
  • Can contain multiple SQL statements
  • Can return result sets or output values
  • Lives inside the database forever

Advantages:

  • Reusability → Call it anytime with one line
  • Security → Users can execute procedure without seeing underlying tables
  • Performance → Pre-compiled, faster than sending many queries
  • Maintainability → Change logic in one place

2. CREATE PROCEDURE – Basic Syntax

Syntax:

SQL

Why DELIMITER? Because procedures can have semicolons ; inside them — we temporarily change the statement ender to // so MySQL doesn’t get confused.

Example 1 – Simple procedure: Get all active students

SQL

How to call it:

SQL

You’ll see the list of active students — just like running the SELECT!

3. Parameters: IN, OUT, INOUT

Type Meaning Example
IN Input parameter (default) Pass value to procedure
OUT Output parameter (procedure sets it) Get value back from procedure
INOUT Both input and output Modify value and get it back

Example 2 – Procedure with IN parameter: Get students from a specific city

SQL

Call it:

SQL

Example 3 – Procedure with OUT parameter: Count active students

SQL

Call it:

SQL

Example 4 – INOUT parameter: Increase fees by a percentage

SQL

Call it:

SQL

4. CALL Procedure – How to Execute

Just write:

SQL

You can call procedures from:

  • MySQL Workbench
  • PHP/Python/Node.js code
  • Other stored procedures

5. User-Defined Functions (UDFs) – Return a Single Value

Syntax:

SQL

Example – Function: Calculate approximate age

SQL

Use it like any built-in function:

SQL

Note: DETERMINISTIC means same input → always same output (helps optimizer)

6. Variables, IF/CASE, Loops – Make Procedures Smarter

Variables:

SQL

IF / CASE:

SQL

CASE:

SQL

Loops – WHILE / REPEAT / LOOP

SQL

Example – Procedure: Enroll student in course with fee validation

SQL

Call it:

SQL

That’s it for Chapter 15! 🎉 You now know how to write your own reusable code inside MySQL — procedures for actions, functions for calculations!

Homework for today (do it right now – very important!) Run these and paste the output of the final SELECTs:

SQL

Paste the results of the two SELECTs — I’ll check them!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *