SQL stored procedures are sets of SQL statements saved and stored in a database. They can be executed on demand to perform data manipulation and validation tasks, reducing the need to write repetitive SQL code for common operations. Stored procedures are helpful in database management by promoting efficiency and reusability. In addition, they support enhanced database security and maintainability. In this article, we will discuss how to create and execute SQL stored procedures, common use cases, and best practices.
As we get started, I highly recommend taking DataCamp’s Introduction to SQL and Learn SQL courses to learn the foundational knowledge of extracting and analyzing data using SQL. Also, the SQL Basics Cheat Sheet, which you can download, is a helpful reference because it has all the most common SQL functions.
What is Stored Procedure in SQL?
A stored procedure in SQL is a collection of SQL statements saved and stored within the database. The purpose of the SQL stored procedure is to perform a sequence of operations on a database, such as querying, inserting, updating, or deleting data.
Unlike regular SQL queries, executed as separate commands, stored procedures encapsulate a set of SQL statements, making it easy to reuse the code without having to write SQL commands repeatedly.
The benefits of SQL stored procedures include the following:
Code reusability: Once a stored procedure is created, it can be called as many times as needed, eliminating redundancy in SQL code.
Enhanced performance: Stored procedures often execute faster because they are precompiled and stored on the database server, reducing network latency and compilation time.
Security: Stored procedures can improve data security and control over sensitive data access by granting users permission to execute a stored procedure without direct access to tables.
Basic syntax and structure
The syntax for creating a stored procedure may vary slightly depending on the database system (e.g., MySQL, SQL Server, Oracle). Below is a general example using SQL Server syntax:
-- Create a stored procedure named ProcedureNameCREATEPROCEDURE ProcedureName
@Parameter1INT,@Parameter2VARCHAR(50)ASBEGIN-- SQL statements go hereSELECT*FROM TableName WHERE Column1 =@Parameter1AND Column2 =@Parameter2;END;
CREATE PROCEDURE: This command is used to define a new stored procedure.
ProcedureName: The name given to the stored procedure. It should be unique within the database.
@Parameter1, @Parameter2: Parameters are optional; they allow the procedure to receive data inputs. Each parameter is defined with a @ symbol and a data type (e.g., INT, VARCHAR(50)).
AS BEGIN...END: The SQL statements within BEGIN and END form the body of the procedure, where the main logic is executed. The procedure retrieves records from a table based on specific conditions in this example.
Input and output parameters
The input and output parameters allow you to pass values to and from a stored procedure.
For example, if @Parameter1 is defined as an input parameter, it can be assigned any value when the procedure is called, affecting the SQL logic or output. In the example below, the @UserID parameter retrieves data specific to the provided UserID.
-- Create a procedure to retrieve data for a specific user by UserIDCREATEPROCEDURE GetUserData
-- Input parameter: ID of the user to retrieve@UserIDINTASBEGIN-- Select all columns from Users where UserID matches the input parameterSELECT*FROM Users WHERE UserID =@UserID;END;
Output parameters, defined by the OUTPUT keyword, allow a stored procedure to send a value back to the calling environment. For example, if a procedure calculates a discount, it could use an output parameter to pass it back to the calling program.
-- Create a procedure to calculate the discounted priceCREATEPROCEDURE CalculateDiscount
@PriceDECIMAL(10,2),@DiscountRateDECIMAL(5,2),@FinalPriceDECIMAL(10,2) OUTPUT -- Output: final price after discountASBEGIN-- Calculate final price by applying the discount rate to the original priceSET@FinalPrice=@Price*(1-@DiscountRate);END;
-- Declare a variable to store the final price after discountDECLARE@FinalPriceDECIMAL(10,2);-- Execute the CalculateDiscount procedure with a price of 100 and a 10% discount -- Store the output in the @FinalPrice variableEXEC CalculateDiscount @Price=100,@DiscountRate=0.1,@FinalPrice=@FinalPrice OUTPUT;-- Select and display the final discounted priceSELECT@FinalPriceAS FinalPrice;
As I had mentioned, executing a stored procedure in SQL can be done in different ways depending on the database system and the tools used.
Creating stored procedures in MySQL
Creating a stored procedure in MySQL involves defining the procedure's name, parameters, and the SQL statements that make up its body. The following example creates a procedure called GetEmployeeDetails that takes EmployeeID as an input parameter and retrieves details for that specific employee.
DELIMITER $
-- Create a procedure to retrieve details for a specific employee by EmployeeIDCREATEPROCEDURE GetEmployeeDetails(IN EmployeeID INT)BEGIN-- Select all columns from Employees where EmployeeID matches the input parameter SELECT*FROM Employees WHERE EmployeeID = EmployeeID;END$
DELIMITER;Drivs av
Executing stored procedures in MySQL
The most common way to execute a stored procedure is using SQL commands. In MySQL, we use the CALL command to execute the stored procedure.
Using the defined GetEmployeeDetails procedure, the execution query would look like this:
-- Execute the stored procedure to retrieve details for EmployeeID 101CALL GetEmployeeDetails(101);Drivs av
Stored Procedures in SQL Server
SQL Server provides specific syntax and commands for creating, executing, and managing stored procedures. This approach makes it easier to build efficient and reusable SQL routines that can handle complex tasks with minimal repetition.
Creating stored procedures in SQL Server
Creating a stored procedure in SQL Server involves defining the procedure's name, parameters, and the SQL statements that make up its body. The following example creates a procedure called GetEmployeeDetails that takes @EmployeeID as an input parameter and retrieves details for that specific employee.
-- Create a procedure to retrieve details for a specific employee by EmployeeIDCREATEPROCEDURE GetEmployeeDetails
@EmployeeIDINT-- Input parameter: ID of the employee to retrieveASBEGIN-- Select all columns from Employees where EmployeeID matches the input parameterSELECT*FROM Employees WHERE EmployeeID =@EmployeeID;END;
In SQL Server, the EXEC or EXECUTE command calls a stored procedure. The following example shows how to execute the stored procedure GetEmployeeDetails using specific input parameters.
-- Execute the GetEmployeeDetails procedure with the EmployeeIDset to 102EXEC GetEmployeeDetails @EmployeeID=102;
You can also execute the output parameters by declaring the variable in the command. In the following example, @TotalSales is declared a variable to receive the output from CalculateTotalSales.
-- Declare a variable to store the total sales amountDECLARE@TotalSalesDECIMAL(10,2);-- Execute CalculateTotalSales for SalespersonID 5, store the result in @TotalSalesEXEC CalculateTotalSales @SalespersonID=5,@TotalSales=@TotalSales OUTPUT;-- Display the total sales amountSELECT@TotalSalesAS TotalSales;
I recommend taking our Introduction to SQL Server course to understand SQL Server's different functionalities for querying data. Also, consider our full SQL Server Developer career track, which will not only equip you with the skills to create, update, and execute stored procedures, but will also help you with aggregate functions, joining, inserting, and deleting tables, and much more.
Common Uses for Stored Procedures
SQL stored procedures are useful in scenarios where repetitive complex tasks are required. The following are real-world applications of stored procedures in data management and business operations.
Data validation and integrity enforcement
Stored procedures can be used to validate data before update or insertion. In the example below, a stored procedure checks that a customer’s email is unique before inserting a new record into the Customers table, ensuring data consistency. This centralizes validation logic within the database, reducing redundancy and ensuring uniform enforcement across different applications.
-- Create a procedure to add a new customer, checking for duplicate emailCREATEPROCEDURE AddCustomer
@CustomerNameVARCHAR(50),@CustomerEmailVARCHAR(50)ASBEGIN-- Check if the email already exists in the Customers tableIFEXISTS(SELECT1FROM Customers WHERE Email =@CustomerEmail)-- Throw an error if the email is already in use
THROW 50000,'Email already exists.',1;ELSE-- Insert new customer details if email is uniqueINSERTINTO Customers (Name, Email)VALUES(@CustomerName,@CustomerEmail);END;
You can also use stored procedures to generate regular reports or process large datasets. For example, a stored procedure could aggregate daily sales data from an e-commerce platform and store it in a reporting table, making it easier for teams to access sales insights without running complex queries.
-- Create a procedure to generate a daily sales reportCREATEPROCEDURE GenerateDailySalesReport
ASBEGIN-- Insert today's date and total sales into the SalesReport tableINSERTINTO SalesReport (ReportDate, TotalSales)-- Select current date and sum of sales for today from Sales tableSELECT CAST(GETDATE()ASDATE),SUM(SalesAmount)FROM Sales
WHERE SaleDate = CAST(GETDATE()ASDATE);END;
By using stored procedures, you can ensure multiple operations are executed as a single transaction. For example, in a banking system, a stored procedure can handle both debit and credit actions in a funds transfer, making sure both actions succeed or fail together.
-- Create a procedure to transfer funds between accountsCREATEPROCEDURE TransferFunds
@SenderAccountINT,@ReceiverAccountINT,@AmountDECIMAL(10,2)ASBEGINBEGINTRANSACTION;-- Start a transaction to ensure atomicity-- Deduct the specified amount from the sender's account balanceUPDATE Accounts SET Balance = Balance -@AmountWHERE AccountID =@SenderAccount;-- Add the specified amount to the receiver's account balanceUPDATE Accounts SET Balance = Balance +@AmountWHERE AccountID =@ReceiverAccount;-- Check for errors and rollback if any occurred; otherwise, commit the transactionIF @@ERROR<>0ROLLBACKTRANSACTION;-- Undo all changes if an error occurredELSECOMMITTRANSACTION;-- Confirm changes if no errorsEND;
You can also use SQL stored to control data access to sensitive information. For example, a stored procedure can limit direct table access by allowing users to call a procedure that retrieves only relevant fields, such as account balances, without transaction details.
-- Create a procedure to retrieve account balance, with authorization checkCREATEPROCEDURE GetAccountBalance
@AccountIDINT,@UserIDINTASBEGIN-- Check if the account exists and is owned by the specified userIFEXISTS(SELECT1FROM Accounts WHERE AccountID =@AccountIDAND UserID =@UserID)-- If authorized, select and return the account balanceSELECT Balance FROM Accounts WHERE AccountID =@AccountID;ELSE-- If unauthorized, throw an error
THROW 50000,'Unauthorized access.',1;END;
Stored procedures are also used to load, transform, and migrate data between systems. A stored procedure can automate data extraction from a source database, transform it as needed, and insert it into a target table, simplifying data integration for reporting or analysis.
CREATEPROCEDURE ETLProcess
ASBEGIN-- ExtractINSERTINTO StagingTable
SELECT*FROM SourceTable WHERE Condition;-- TransformUPDATE StagingTable SET ColumnX = TransformationLogic(ColumnX);-- LoadINSERTINTO TargetTable
SELECT*FROM StagingTable;END;
Writing efficient and maintainable stored procedures ensures your database performs optimally. The following are the tips for writing stored procedures for your SQL databases.
Use Consistent Naming Conventions: To make stored procedures easy to identify and understand, use a consistent and descriptive naming format. Also, avoid the sp_ Prefix in SQL Server reserved for system procedures to prevent potential conflicts and performance issues.
Implement Error Handling: Wrap SQL statements in TRY...CATCH blocks to catch and handle errors and maintain data integrity.
Optimize for Performance: Minimize the use of cursors as they can be slow and resource-intensive. Instead, try using set-based operations, which are generally more efficient. Also, index the frequently used columns and avoid complex joins in large tables to reduce memory overhead and improve efficiency.
Parameterize Stored Procedures: Use parameters instead of hardcoded values to allow you to pass dynamic values into your procedure, making it more flexible and reusable.
Check out our Intermediate SQL course to learn more about using aggregate functions and joins to filter data. Also, try out our SQL Server Fundamentals and SQL Fundamentals skill tracks to improve your joining tables and data analysis skills.
Conclusion
SQL stored procedures enhance code reusability and performance optimization in database management. Stored procedures also enhance database security through controlled access and ensuring data integrity. As a data practitioner, I encourage you to practice creating and executing stored procedures to master the best database management practices.
If you are interested in becoming a proficient data analyst, check out our Associate Data Analyst in SQL career track to learn the necessary skills. The Reporting in SQL course is also appropriate if you want to learn how to build professional dashboards using SQL. Finally, I recommend obtaining the SQL Associate Certification to demonstrate your mastery of using SQL for data analysis and stand out among other data professionals.
Data Science Technical Writer with hands-on experience in data analytics, business intelligence, and data science. I write practical, industry-focused content on SQL, Python, Power BI, Databricks, and data engineering, grounded in real-world analytics work. My writing bridges technical depth and business impact, helping professionals turn data into confident decisions.
Stored Procedure FAQs
What is a stored procedure in SQL?⌄
A stored procedure is a collection of SQL statements that perform a specific task stored within the database for reuse.
How do stored procedures differ from regular SQL queries?⌄
Unlike individual queries, stored procedures are precompiled and can include control-of-flow statements, parameters, and error handling, allowing for more complex operations.
What is the difference between input and output parameters in stored procedures?⌄
Input parameters allow users to pass values into the procedure, while output parameters return values from the procedure to the caller.
Are stored procedures database-specific?⌄
Stored procedures can be specific to each SQL database management system (e.g., SQL Server, MySQL, Oracle), with syntax variations across platforms.
Understand the SQL order of execution and how its different from the order of writing. Write accurate and optimized queries for improved performance and avoid common mistakes in query design.
Learn how to use SQL triggers to automate tasks, maintain data integrity, and enhance database performance. Try practical examples like the CREATE, ALTER, and DROP commands in MySQL and Oracle.
SQL stored procedures are sets of SQL statements saved and stored in a database. They can be executed on demand to perform data manipulation and validation tasks, reducing the need to write repetitive SQL code for common operations. Stored procedures are helpful in database management by promoting efficiency and reusability. In addition, they support enhanced database security and maintainability. In this article, we will discuss how to create and execute SQL stored procedures, common use cases, and best practices.
As we get started, I highly recommend taking DataCamp’s Introduction to SQL and Learn SQL courses to learn the foundational knowledge of extracting and analyzing data using SQL. Also, the SQL Basics Cheat Sheet, which you can download, is a helpful reference because it has all the most common SQL functions.
What is Stored Procedure in SQL?
A stored procedure in SQL is a collection of SQL statements saved and stored within the database. The purpose of the SQL stored procedure is to perform a sequence of operations on a database, such as querying, inserting, updating, or deleting data.
Unlike regular SQL queries, executed as separate commands, stored procedures encapsulate a set of SQL statements, making it easy to reuse the code without having to write SQL commands repeatedly.
The benefits of SQL stored procedures include the following:
Basic syntax and structure
The syntax for creating a stored procedure may vary slightly depending on the database system (e.g., MySQL, SQL Server, Oracle). Below is a general example using SQL Server syntax:
In the above syntax;
CREATE PROCEDURE: This command is used to define a new stored procedure.
ProcedureName: The name given to the stored procedure. It should be unique within the database.
@Parameter1, @Parameter2: Parameters are optional; they allow the procedure to receive data inputs. Each parameter is defined with a
@symbol and a data type (e.g.,INT,VARCHAR(50)).AS BEGIN...END: The SQL statements within
BEGINandENDform the body of the procedure, where the main logic is executed. The procedure retrieves records from a table based on specific conditions in this example.Input and output parameters
The input and output parameters allow you to pass values to and from a stored procedure.
For example, if
@Parameter1is defined as an input parameter, it can be assigned any value when the procedure is called, affecting the SQL logic or output. In the example below, the@UserIDparameter retrieves data specific to the providedUserID.Output parameters, defined by the
OUTPUTkeyword, allow a stored procedure to send a value back to the calling environment. For example, if a procedure calculates a discount, it could use an output parameter to pass it back to the calling program.To call this procedure, you would use;
Stored Procedures in MySQL
As I had mentioned, executing a stored procedure in SQL can be done in different ways depending on the database system and the tools used.
Creating stored procedures in MySQL
Creating a stored procedure in MySQL involves defining the procedure's name, parameters, and the SQL statements that make up its body. The following example creates a procedure called
GetEmployeeDetailsthat takesEmployeeIDas an input parameter and retrieves details for that specific employee.Executing stored procedures in MySQL
The most common way to execute a stored procedure is using SQL commands. In MySQL, we use the
CALLcommand to execute the stored procedure.Using the defined
GetEmployeeDetailsprocedure, the execution query would look like this:Stored Procedures in SQL Server
SQL Server provides specific syntax and commands for creating, executing, and managing stored procedures. This approach makes it easier to build efficient and reusable SQL routines that can handle complex tasks with minimal repetition.
Creating stored procedures in SQL Server
Creating a stored procedure in SQL Server involves defining the procedure's name, parameters, and the SQL statements that make up its body. The following example creates a procedure called
GetEmployeeDetailsthat takes@EmployeeIDas an input parameter and retrieves details for that specific employee.Executing stored procedures in SQL Server
In SQL Server, the
EXECorEXECUTEcommand calls a stored procedure. The following example shows how to execute the stored procedureGetEmployeeDetailsusing specific input parameters.You can also execute the output parameters by declaring the variable in the command. In the following example,
@TotalSalesis declared a variable to receive the output fromCalculateTotalSales.I recommend taking our Introduction to SQL Server course to understand SQL Server's different functionalities for querying data. Also, consider our full SQL Server Developer career track, which will not only equip you with the skills to create, update, and execute stored procedures, but will also help you with aggregate functions, joining, inserting, and deleting tables, and much more.
Common Uses for Stored Procedures
SQL stored procedures are useful in scenarios where repetitive complex tasks are required. The following are real-world applications of stored procedures in data management and business operations.
Data validation and integrity enforcement
Stored procedures can be used to validate data before update or insertion. In the example below, a stored procedure checks that a customer’s email is unique before inserting a new record into the
Customerstable, ensuring data consistency. This centralizes validation logic within the database, reducing redundancy and ensuring uniform enforcement across different applications.Automated data processing and reporting
You can also use stored procedures to generate regular reports or process large datasets. For example, a stored procedure could aggregate daily sales data from an e-commerce platform and store it in a reporting table, making it easier for teams to access sales insights without running complex queries.
Transaction management
By using stored procedures, you can ensure multiple operations are executed as a single transaction. For example, in a banking system, a stored procedure can handle both debit and credit actions in a funds transfer, making sure both actions succeed or fail together.
Access control and data security
You can also use SQL stored to control data access to sensitive information. For example, a stored procedure can limit direct table access by allowing users to call a procedure that retrieves only relevant fields, such as account balances, without transaction details.
Data migration and ETL processes
Stored procedures are also used to load, transform, and migrate data between systems. A stored procedure can automate data extraction from a source database, transform it as needed, and insert it into a target table, simplifying data integration for reporting or analysis.
Best Practices for Stored Procedures
Writing efficient and maintainable stored procedures ensures your database performs optimally. The following are the tips for writing stored procedures for your SQL databases.
Use Consistent Naming Conventions: To make stored procedures easy to identify and understand, use a consistent and descriptive naming format. Also, avoid the
sp_Prefix in SQL Server reserved for system procedures to prevent potential conflicts and performance issues.Implement Error Handling: Wrap SQL statements in
TRY...CATCHblocks to catch and handle errors and maintain data integrity.Optimize for Performance: Minimize the use of cursors as they can be slow and resource-intensive. Instead, try using set-based operations, which are generally more efficient. Also, index the frequently used columns and avoid complex joins in large tables to reduce memory overhead and improve efficiency.
Parameterize Stored Procedures: Use parameters instead of hardcoded values to allow you to pass dynamic values into your procedure, making it more flexible and reusable.
Check out our Intermediate SQL course to learn more about using aggregate functions and joins to filter data. Also, try out our SQL Server Fundamentals and SQL Fundamentals skill tracks to improve your joining tables and data analysis skills.
Conclusion
SQL stored procedures enhance code reusability and performance optimization in database management. Stored procedures also enhance database security through controlled access and ensuring data integrity. As a data practitioner, I encourage you to practice creating and executing stored procedures to master the best database management practices.
If you are interested in becoming a proficient data analyst, check out our Associate Data Analyst in SQL career track to learn the necessary skills. The Reporting in SQL course is also appropriate if you want to learn how to build professional dashboards using SQL. Finally, I recommend obtaining the SQL Associate Certification to demonstrate your mastery of using SQL for data analysis and stand out among other data professionals.