Stored Procedures and Functions
# 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
CALLcommand.
- 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-stepJOIN 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.
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.
*(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 standardSELECT statements (just like you use SUM() or COUNT()).
Let's create a Function that calculates a 15% discount on a given price.
7. Using the Custom Function
Now we can use our customCalculateDiscount() function seamlessly in our daily queries!
8. Mini Project: E-Commerce Security
Why do banks use Stored Procedures? Security. A Database Administrator can block the PHP web server from havingINSERT, 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 theBEGINblock, 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. What command is used to execute a saved Stored Procedure?
-
2.
What is the fundamental difference between a Procedure and a Function regarding the
RETURNkeyword?
12. SQL Challenges
Write the execution command required to run a pre-existing Stored Procedure namedArchiveOldUsers which accepts a single integer parameter (e.g., passing the number 2020 as the year to archive).
13. MCQ Quiz with Answers
What is the primary architectural advantage of utilizing Stored Procedures in an enterprise database system?
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 individualUPDATEstatements 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 useIF/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 typeCALL 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.