Lab 03: Stored Procedures & Functions

Time: 40 minutes | Level: Practitioner | DB: MySQL 8.0 + PostgreSQL 15

Stored procedures bundle SQL logic server-side for reuse, security, and performance. MySQL uses PROCEDURE (no return value); PostgreSQL uses FUNCTION (returns a value or table).


Step 1 — MySQL: Setup and Basic Procedure

-- Create database and table
CREATE DATABASE labdb;
USE labdb;

CREATE TABLE orders (
  id         INT AUTO_INCREMENT PRIMARY KEY,
  customer   VARCHAR(100),
  product    VARCHAR(100),
  quantity   INT,
  unit_price DECIMAL(10,2),
  total      DECIMAL(10,2),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO orders (customer, product, quantity, unit_price, total) VALUES
  ('Alice', 'Widget A',  5,  9.99,  49.95),
  ('Bob',   'Widget B',  3, 14.99,  44.97),
  ('Alice', 'Gadget X',  2, 29.99,  59.98),
  ('Carol', 'Widget A', 10,  9.99,  99.90),
  ('Bob',   'Gadget Y',  1, 49.99,  49.99);

📸 Verified Output:


Step 2 — MySQL: IN / OUT / INOUT Parameters

📸 Verified Output:

💡 MySQL client requires DELIMITER // only in the interactive shell. When sourcing a .sql file (via <), the default ; delimiter works fine.


Step 3 — MySQL: IF / WHILE Control Flow

📸 Verified Output:


Step 4 — MySQL: LOOP and Cursor Pattern

💡 Cursors are row-by-row and slow on large data. Prefer set-based UPDATE unless per-row business logic is unavoidable.


Step 5 — PostgreSQL: CREATE FUNCTION with PL/pgSQL

📸 Verified Output:


Step 6 — PostgreSQL: DECLARE and Exception Handling

💡 EXCEPTION WHEN OTHERS THEN catches all unhandled errors. Use SQLERRM for the message and SQLSTATE for the error code.


Step 7 — PostgreSQL: RETURNS TABLE with Set-Returning Functions


Step 8 — Capstone: Audit-Enabled Order Processing

Build a MySQL procedure that inserts an order and logs the action:


Summary

Feature
MySQL
PostgreSQL

Create

CREATE PROCEDURE

CREATE FUNCTION

Return value

OUT params only

RETURNS type or RETURNS TABLE

Language

MySQL procedural SQL

PL/pgSQL (or Python, JS, etc.)

Call

CALL proc_name(args)

SELECT func_name(args)

Variables

DECLARE v INT; SET v = 1

DECLARE v INT; v := 1;

Loops

LOOP, WHILE, REPEAT

LOOP, FOR, WHILE

Error handling

SIGNAL SQLSTATE

RAISE EXCEPTION

Cursors

DECLARE cur CURSOR FOR

FOR row IN query LOOP

Last updated