Skip to main content
SQL Fundamentals
CHAPTER 24 Beginner

SQL Stored Procedures | Functions and Database Logic

Updated: May 16, 2026
15 min read

# CHAPTER 24

Stored Procedures and Functions

1. Introduction

Normally, your application (PHP, Node.js, Python) contains the "Business Logic". It does the math, writes the SQL queries, and sends them over the internet to the Database. But sending 10 massive queries across a network takes time. What if we could write the business logic *directly inside the database engine*? This is achieved using Stored Procedures and User-Defined Functions (UDFs). In this chapter, we will learn how to transform SQL from a simple query language into a fully functional programming environment.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the architectural purpose of Stored Procedures.
  • Create a Stored Procedure using parameters (IN, OUT).
  • Execute a saved procedure using the CALL command.
  • Differentiate between a Stored Procedure and a SQL Function.
  • Understand the performance benefits of encapsulated logic.

3. What is a Stored Procedure?

A Stored Procedure is a prepared SQL code block that you can save directly into the database schema, so you can reuse it over and over again. Instead of a PHP server sending a massive 5-step JOIN and UPDATE transaction over the network, the PHP server simply sends a single command: "Hey Database, run the 'Checkout' procedure for User 5." The database does all the heavy lifting locally on its own CPU.

4. Creating a Stored Procedure

*(Note: The exact syntax for procedures varies slightly between MySQL, PostgreSQL, and SQL Server. This example uses standard MySQL syntax).*

Let's create a procedure that automatically transfers an employee to a new department and logs the transfer date.

sql
1234567891011121314151617181920
-- Change the delimiter so MySQL doesn't get confused by the internal semicolons
DELIMITER //

CREATE PROCEDURE TransferEmployee(
    IN emp_id INT, 
    IN new_dept_id INT
)
BEGIN
    -- Step 1: Update the employee table
    UPDATE employees 
    SET dept_id = new_dept_id 
    WHERE id = emp_id;
    
    -- Step 2: Insert a record into the audit log!
    INSERT INTO transfer_logs (employee_id, old_dept, new_dept, transfer_date)
    VALUES (emp_id, 'Unknown', new_dept_id, NOW());
END //

-- Reset the delimiter
DELIMITER ;

5. Executing a Stored Procedure (CALL)

Once the procedure is permanently saved in the database schema, invoking it is incredibly simple. You use the CALL command.
sql
12
-- Transfer Employee #105 to Department #3 instantly!
CALL TransferEmployee(105, 3);

*(Result: The database executes both the UPDATE and the INSERT queries internally in a fraction of a millisecond!)*

6. What is a SQL Function?

A Function is very similar to a Procedure, but with a strict mathematical rule: It MUST return a single value, and it cannot permanently alter data (it usually only reads data). You use Functions inside of standard SELECT statements (just like you use SUM() or COUNT()).

Let's create a Function that calculates a 15% discount on a given price.

sql
1234567891011121314
DELIMITER //

CREATE FUNCTION CalculateDiscount(original_price DECIMAL(10,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
    DECLARE discounted_price DECIMAL(10,2);
    SET discounted_price = original_price * 0.85;
    
    -- A function MUST return a value!
    RETURN discounted_price; 
END //

DELIMITER ;

7. Using the Custom Function

Now we can use our custom CalculateDiscount() function seamlessly in our daily queries!
sql
12345
SELECT 
    product_name, 
    price AS 'Original Price',
    CalculateDiscount(price) AS 'Black Friday Price'
FROM products;

8. Mini Project: E-Commerce Security

Why do banks use Stored Procedures? Security. A Database Administrator can block the PHP web server from having INSERT, UPDATE, or DELETE permissions on the financial_ledgers table. Instead, the DBA grants the PHP server permission to CALL ExecutePayment(). This means the PHP server cannot accidentally run a rogue DELETE command; it can ONLY run the pre-approved, strictly controlled logic inside the procedure!

9. Common Mistakes

  • Syntax Variations: If you copy and paste a Stored Procedure tutorial written for Microsoft SQL Server (T-SQL) into a PostgreSQL database (PL/pgSQL), it will immediately crash. Procedural languages are highly specific to the database engine.
  • The Delimiter Error: When writing procedures in MySQL Workbench or CLI, if you forget to change the DELIMITER //, the engine will execute the very first semicolon ; inside the BEGIN block, shattering the procedure creation.

10. Best Practices

  • Where does Business Logic Belong? The industry is split. Some architects put all logic in Stored Procedures (making the database incredibly powerful but hard to migrate). Modern web architects often prefer putting logic in the Node.js/PHP backend (making the code easier to version control with Git) and using the database purely for dumb storage. Balance is key.

11. Exercises

  1. 1. What command is used to execute a saved Stored Procedure?
  1. 2. What is the fundamental difference between a Procedure and a Function regarding the RETURN keyword?

12. SQL Challenges

Write the execution command required to run a pre-existing Stored Procedure named ArchiveOldUsers which accepts a single integer parameter (e.g., passing the number 2020 as the year to archive).
sql
1
CALL ArchiveOldUsers(2020);

13. MCQ Quiz with Answers

Question 1

What is the primary architectural advantage of utilizing Stored Procedures in an enterprise database system?

Question 2

In SQL programming, what is the strict structural distinction between a Stored Procedure and a User-Defined Function (UDF)?

14. Interview Questions

  • Q: Explain the concept of "Network Latency Optimization" regarding Stored Procedures. Why is it faster for a Node.js server to execute CALL ProcessPayroll(); rather than sending 500 individual UPDATE statements over the TCP/IP network?
  • Q: Debate the modern architectural dilemma: Should complex business logic reside in Database Stored Procedures, or in the application backend (e.g., Python/Java)? What are the pros and cons of tying your logic tightly to the database engine?

15. FAQs

Q: Can I use IF/ELSE logic and WHILE loops in SQL? A: Yes! Inside a BEGIN...END block of a Stored Procedure, you can write fully functional IF/THEN/ELSE statements and WHILE loops, making SQL a Turing-complete programming language!

16. Summary

You are now programming at the lowest, fastest level possible. By encapsulating logic into Stored Procedures and calculating data on the fly with User-Defined Functions, you can execute massive, complex operations with zero network latency and impenetrable security.

17. Next Chapter Recommendation

Procedures require you to actively type CALL to run them. But what if we want the database to run a piece of code *automatically* without us ever asking? What if we want the database to automatically generate a log every time an employee is deleted? In Chapter 25: Triggers and Database Automation, we will learn how to make the database react to events autonomously.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·