While application code (Node.js, Python, Java) typically handles business logic, relational databases allow you to compile and execute procedural code directly inside the database engine using Stored Procedures and User-Defined Functions.
Running logic inside the database eliminates network latency when performing multi-step batch operations and provides a secure abstraction boundary where applications execute pre-authorized routines rather than accessing raw tables.
1. Stored Procedures vs. Functions
| Feature | Stored Procedure (PROCEDURE) | User-Defined Function (FUNCTION) |
|---|---|---|
| Invocation | Called via CALL ProcedureName(args) | Called inline in queries: SELECT Func(col) FROM t |
| Return Values | Returns 0, 1, or multiple result sets, or uses OUT parameters | Must return a single scalar value via RETURN |
| Data Modification | Fully supports INSERT, UPDATE, DELETE (DML) | Restricted; usually read-only / deterministic calculations |
| Transactions | Can manage transactions (START TRANSACTION, COMMIT) | Cannot initiate or commit transactions |
2. The DELIMITER Command Explained
By default, MySQL treats the semicolon (;) as the statement terminator. However, a stored procedure contains dozens of internal SQL statements that each end with a semicolon!
To tell the MySQL parser not to execute the code until the entire procedure definition is complete, we temporarily change the delimiter to a custom sequence (conventionally $$ or //):
DELIMITER $$
CREATE PROCEDURE DemoProcedure()
BEGIN
-- Internal statements end with semicolons:
SELECT 'Step 1' AS msg;
SELECT 'Step 2' AS msg;
END$$
DELIMITER ; -- Reset delimiter back to standard semicolon
3. Parameters in Stored Procedures: IN, OUT, and INOUT
IN(Default): Passes a value from the caller into the procedure (read-only inside the procedure).OUT: Passes a value from the procedure back out to the caller.INOUT: Initialized by the caller, modified by the procedure, and returned back out.
DELIMITER $$
CREATE PROCEDURE ProcessOrder(
IN p_user_id INT,
IN p_amount DECIMAL(10,2),
OUT p_status VARCHAR(20),
OUT p_order_id INT
)
BEGIN
DECLARE v_current_balance DECIMAL(10,2);
-- Query current balance
SELECT balance INTO v_current_balance
FROM bank_accounts
WHERE user_id = p_user_id;
IF v_current_balance >= p_amount THEN
-- Deduct balance
UPDATE bank_accounts
SET balance = balance - p_amount
WHERE user_id = p_user_id;
-- Create order record
INSERT INTO orders (user_id, amount, status)
VALUES (p_user_id, p_amount, 'completed');
SET p_order_id = LAST_INSERT_ID();
SET p_status = 'APPROVED';
ELSE
SET p_order_id = 0;
SET p_status = 'INSUFFICIENT_FUNDS';
END IF;
END$$
DELIMITER ;
-- Calling the procedure with session variables:
CALL ProcessOrder(1, 150.00, @order_status, @new_id);
SELECT @order_status AS status, @new_id AS generated_order_id;
4. User-Defined Scalar Functions
Functions take input arguments, perform calculations, and return a single scalar value. They can be utilized directly in SELECT, WHERE, and ORDER BY clauses:
DELIMITER $$
CREATE FUNCTION CalculateTax(subtotal DECIMAL(10,2), tax_rate DECIMAL(4,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
RETURN ROUND(subtotal * (tax_rate / 100), 2);
END$$
DELIMITER ;
-- Use the function inline just like built-in MySQL functions:
SELECT
product,
amount,
CalculateTax(amount, 8.25) AS sales_tax,
amount + CalculateTax(amount, 8.25) AS grand_total
FROM orders;
5. Control Flow: Conditionals & Loops
Stored procedures support complete procedural control structures:
-- IF-ELSEIF-ELSE
IF condition THEN
-- statements
ELSEIF other_condition THEN
-- statements
ELSE
-- statements
END IF;
-- WHILE Loop
WHILE count < 10 DO
SET count = count + 1;
END WHILE;
6. Pros and Cons: Database Logic vs. Application Logic
| Advantages | Disadvantages |
|---|---|
| Reduced Network Overhead: Complex batch logic runs entirely in-memory on the DB server without dozens of roundtrips. | Difficult Version Control & CI/CD: Harder to test, lint, and deploy compared to standard application code. |
Security Abstraction: Applications only need EXECUTE permission; tables remain completely hidden. | Database CPU Bottleneck: Database compute scales vertically, which is far more expensive than scaling app servers horizontally. |
| Centralized Business Rules: Shared by multiple applications (e.g. Web app, Mobile app, ETL pipelines). | Vendor Lock-in: MySQL procedural SQL (BEGIN...END) cannot run on PostgreSQL, Oracle, or SQL Server. |