Chapter 18: Stored Procedures, Functions, and Triggers

This is where SQL becomes almost like a real programming language!

Up until now, we’ve been writing queries directly every time we need something. But in real-world applications (especially big systems like e-commerce, banking, or hospital software), you don’t want to send the same complex SQL over and over again from your application code.

That’s where Stored Procedures, Functions, and Triggers come in:

  • Stored Procedures → Like saved mini-programs you can call by name
  • Functions → Like procedures, but they return a value (can be used inside SELECT)
  • Triggers → Automatic code that runs by itself when something happens (INSERT, UPDATE, DELETE)

We’ll use our bookshop database and go very deep with realistic examples.

1. Stored Procedures – CREATE PROCEDURE

A stored procedure is a saved block of SQL code that you can call like a function.

Basic Syntax (MySQL / MariaDB):

SQL

Example 1 – Simple procedure: Get all books by an author

SQL

How to call it:

SQL

Example 2 – Procedure with multiple parameters + OUT parameter

SQL

Call it:

SQL

Result might be:

total_books total_stock avg_price
2 215 289.50

2. Functions – CREATE FUNCTION

A function is similar to a procedure but must return a single value — so you can use it inside SELECT, WHERE, etc.

Syntax:

SQL

Example 1 – Function: Calculate discounted price

SQL

Use it in a query:

SQL

Example 2 – Function: Get book age in years

SQL

Use it:

SQL

Key difference: Procedures vs Functions

  • Procedure: CALL it, can have OUT parameters, no return value in SELECT
  • Function: Can be used inside SELECT / WHERE, must RETURN one value

3. Triggers – Automatic Code That Runs on Events

A trigger is SQL code that automatically executes when something happens:

  • BEFORE INSERT / UPDATE / DELETE
  • AFTER INSERT / UPDATE / DELETE

Common uses:

  • Automatically update last_updated timestamp
  • Prevent invalid data (e.g., negative stock)
  • Log changes (audit trail)
  • Auto-calculate totals

Syntax:

SQL

Example 1 – BEFORE INSERT: Prevent negative stock

SQL

Example 2 – AFTER UPDATE: Update last_updated automatically

SQL

Better version (BEFORE UPDATE – more efficient):

SQL

Example 3 – AFTER INSERT: Log new book addition

SQL

Example 4 – BEFORE DELETE: Prevent deletion if stock > 0

SQL

Full Realistic Example – Putting It All Together

SQL

You may also like...

Leave a Reply

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