SQL Stored Procedures β The Ultimate Guide with Examples & FAQs
Introduction β Why Learn SQL Stored Procedures?
Imagine you’re working with a large e-commerce database and need to perform a series of calculations and data validations every time an order is placed. Rewriting the same SQL logic repeatedly is inefficient, error-prone, and hard to maintain.
This is where SQL Stored Procedures come in.
Stored procedures are precompiled SQL code blocks stored in the database that execute logic on demandβenabling code reuse, modularity, performance optimization, and enhanced security.
In this article, you’ll learn:
- What SQL Stored Procedures are and how they work
- Syntax to create, execute, and manage them
- Real-world examples with explanations
- Key differences between procedures and functions
- Best practices, pitfalls, and interview tips
What is a Stored Procedure in SQL?
A Stored Procedure is a set of SQL statements that can perform insert, update, delete, or complex logic operations and are saved in the database for later reuse.
Definition:
βA stored procedure is a named group of SQL statements that are compiled and stored in the database. It can accept input parameters, return multiple results, and include error handling.β
Syntax β How to Create a Stored Procedure
Standard SQL Syntax:
CREATE PROCEDURE procedure_name
AS
BEGIN
-- SQL statements
END;
With Parameters (SQL Server style):
CREATE PROCEDURE GetCustomerOrders @CustomerID INT
AS
BEGIN
SELECT * FROM Orders WHERE CustomerID = @CustomerID;
END;
Tip: Different databases have different syntaxes:
- MySQL: Uses
DELIMITERandBEGIN ... END - SQL Server: Uses
ASfollowed byBEGIN ... END - Oracle: Uses
ISorASwithBEGIN ... END
Executing a Stored Procedure
SQL Server:
EXEC GetCustomerOrders 102;
MySQL:
CALL GetCustomerOrders(102);
Example: Procedure with Input and Output Parameters
CREATE PROCEDURE GetTotalSales
@ProductID INT,
@TotalSales MONEY OUTPUT
AS
BEGIN
SELECT @TotalSales = SUM(Amount)
FROM Sales
WHERE ProductID = @ProductID;
END;
Execution:
DECLARE @OutputSales MONEY;
EXEC GetTotalSales 101, @OutputSales OUTPUT;
PRINT @OutputSales;
Explanation:
@ProductID: input parameter@TotalSales: output parameter populated within the procedureEXEC: invokes the procedurePRINT: displays the result
Benefits of Using Stored Procedures
| Feature | Benefit |
|---|---|
| Precompiled | Faster execution time |
| Reusable Logic | Reduces redundancy |
| Encapsulation & Security | Prevents SQL injection |
| Maintainability | Easy to update logic in one place |
| Supports Transactions | Ensures ACID compliance |
Best Practices
Use meaningful names
β Avoid generic names like Proc1 or TempProcedure.
Include error handling
β Use TRY...CATCH (SQL Server) or DECLARE HANDLER (MySQL) for robustness.
Limit procedure responsibilities
β Follow the Single Responsibility Principle. One proc = one task.
Avoid business logic in procs
β Keep business logic in application code if possible.
Always document input/output params and side effects
Common Pitfalls
Hard-coded values β Avoid static WHERE clauses
No error handling β Can cause silent failures
Overly complex logic β Difficult to debug
Excessive use β Use procedures judiciously over inline SQL
Stored Procedure vs Function β Key Differences
| Feature | Stored Procedure | Function |
|---|---|---|
| Returns | Zero or multiple values | Must return a single value |
| Use in SQL | Called via EXEC/ CALL | Used in SELECT/WHERE |
| Side Effects | Can modify data | Should not modify data |
| Output Parameters | Supported | Not supported |
Advanced: Nested & Dynamic Stored Procedures
Nested Procedure Call:
CREATE PROCEDURE ParentProc
AS
BEGIN
EXEC ChildProc;
END;
Dynamic SQL in Procedure:
CREATE PROCEDURE SearchOrders
@ColumnName NVARCHAR(50),
@SearchValue NVARCHAR(100)
AS
BEGIN
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT * FROM Orders WHERE ' + @ColumnName + ' = ''' + @SearchValue + '''';
EXEC sp_executesql @sql;
END;
Warning: Dynamic SQL can be prone to SQL injection. Use parameterized queries where possible.
Summary β Recap & Next Steps
Stored procedures are powerful tools for optimizing SQL development by modularizing, reusing, and securing SQL logic. They reduce code duplication and allow advanced database operations with controlled inputs and outputs.
Key Takeaways:
- Use
CREATE PROCEDURE,EXEC/CALL, and parameterized logic - Encapsulate business logic and reuse code efficiently
- Handle errors and transactions inside procedures
- Know the difference between procedures and functions
Real-World Note: Most enterprise applications like ERP, e-commerce systems, and finance platforms rely on stored procedures for managing workflows and data integrity.
FAQ β SQL Stored Procedures
What is the purpose of a stored procedure?
To encapsulate frequently executed SQL logic, improve performance, ensure consistency, and enhance security.
Can a stored procedure return multiple result sets?
Yes, many DBMS (like SQL Server, MySQL) allow multiple SELECT statements in one procedure.
What are input and output parameters in stored procedures?
Input parameters pass data into the procedure; output parameters return data back to the caller.
Can I use transactions in stored procedures?
Yes. Use BEGIN TRANSACTION, COMMIT, and ROLLBACK inside procedures to ensure data integrity.
How to debug a stored procedure?
Use print/log statements, try block isolation, or tools like SQL Profiler (SQL Server) or SHOW WARNINGS (MySQL).
Share Now :
