- SQL Tutorial
- SQL - Home
- SQL - Overview
- SQL - RDBMS Concepts
- SQL - Databases
- SQL - Syntax
- SQL - Data Types
- SQL - Operators
- SQL - Expressions
- SQL Database
- SQL - Create Database
- SQL - Drop Database
- SQL - Select Database
- SQL - Rename Database
- SQL - Show Database
- SQL - Backup Database
- SQL Table
- SQL - Create Table
- SQL - Show Tables
- SQL - Rename Table
- SQL - Truncate Table
- SQL - Clone Tables
- SQL - Temporary Tables
- SQL - Alter Tables
- SQL - Drop Table
- SQL - Delete Table
- SQL - Constraints
- SQL Queries
- SQL - Insert Query
- SQL - Select Query
- SQL - Select Into
- SQL - Insert Into Select
- SQL - Update Query
- SQL - Delete Query
- SQL - Sorting Results
- SQL Views
- SQL - Create Views
- SQL - Update Views
- SQL - Drop Views
- SQL - Rename Views
- SQL Operators and Clauses
- SQL - Where Clause
- SQL - Top Clause
- SQL - Distinct Clause
- SQL - Order By Clause
- SQL - Group By Clause
- SQL - Having Clause
- SQL - AND & OR
- SQL - BOOLEAN (BIT) Operator
- SQL - LIKE Operator
- SQL - IN Operator
- SQL - ANY, ALL Operators
- SQL - EXISTS Operator
- SQL - CASE
- SQL - NOT Operator
- SQL - NOT EQUAL
- SQL - IS NULL
- SQL - IS NOT NULL
- SQL - NOT NULL
- SQL - BETWEEN Operator
- SQL - UNION Operator
- SQL - UNION vs UNION ALL
- SQL - INTERSECT Operator
- SQL - EXCEPT Operator
- SQL - Aliases
- SQL Joins
- SQL - Using Joins
- SQL - Inner Join
- SQL - Left Join
- SQL - Right Join
- SQL - Cross Join
- SQL - Full Join
- SQL - Self Join
- SQL - Delete Join
- SQL - Update Join
- SQL - Left Join vs Right Join
- SQL - Union vs Join
- SQL Keys
- SQL - Unique Key
- SQL - Primary Key
- SQL - Foreign Key
- SQL - Composite Key
- SQL - Alternate Key
- SQL Indexes
- SQL - Indexes
- SQL - Create Index
- SQL - Drop Index
- SQL - Show Indexes
- SQL - Unique Index
- SQL - Clustered Index
- SQL - Non-Clustered Index
- Advanced SQL
- SQL - Wildcards
- SQL - Comments
- SQL - Injection
- SQL - Hosting
- SQL - Min & Max
- SQL - Null Functions
- SQL - Check Constraint
- SQL - Default Constraint
- SQL - Stored Procedures
- SQL - NULL Values
- SQL - Transactions
- SQL - Sub Queries
- SQL - Handling Duplicates
- SQL - Using Sequences
- SQL - Auto Increment
- SQL - Date & Time
- SQL - Cursors
- SQL - Common Table Expression
- SQL - Group By vs Order By
- SQL - IN vs EXISTS
- SQL - Database Tuning
- SQL Function Reference
- SQL - Date Functions
- SQL - String Functions
- SQL - Aggregate Functions
- SQL - Numeric Functions
- SQL - Text & Image Functions
- SQL - Statistical Functions
- SQL - Logical Functions
- SQL - Cursor Functions
- SQL - JSON Functions
- SQL - Conversion Functions
- SQL - Datatype Functions
- SQL Useful Resources
- SQL - Questions and Answers
- SQL - Quick Guide
- SQL - Useful Functions
- SQL - Useful Resources
- SQL - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
SQL - Stored Procedures
A stored procedure is a group of pre-compiled SQL statements (prepared SQL code) that can be reused again and again.
They can be used to perform a wide range of database operations such as inserting, updating, or deleting data, generating reports, and performing complex calculations. Stored procedures are very useful because they allow you to encapsulate (bundle) a set of SQL statements as a single unit and execute them repeatedly with different parameters, making it easy to manage and reuse code.
Procedures have similar structure as functions; they accept parameters and perform operations when we call them; but the difference between them is that SQL stored procedures are simpler to write or create, whereas functions have a more rigid structure and support fewer clauses and functionality.
Syntax
The basic syntax to create a stored procedure in SQL is as follows −
CREATE PROCEDURE procedure_name @parameter1 datatype, @parameter2 datatype AS BEGIN -- SQL statements to be executed END
Where,
The CREATE PROCEDURE statement is used to create the procedure. After creating the procedure, we can define any input parameters that the procedure may require. These parameters are preceded by the '@' symbol and followed by their respective data types.
The AS keyword is used to begin the procedure definition. The SQL statements that make up the procedure are placed between the BEGIN and END keywords.
Creating a Procedure
We can create a stored procedure using the CREATE PROCEDURE statement in SQL. Following are the simple steps for creating a stored procedure −
Choose a name for the procedure.
Write the SQL code for the procedure, including to create the procedure in SQL Server.
We can then test the stored procedure by executing it with different input parameters.
Example
To understand it better let us consider the CUSTOMERS table which contains the personal details of customers including their name, age, address and salary etc. as shown below −
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
Now insert values into this table using the INSERT statement as follows −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'kaushik', 23, 'Kota', 2000.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Komal', 22, 'MP', 4500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
The table will be created as −
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+
Now, let's look at a simple example of creating a stored procedure that takes an input parameter and returns a result set.
In the following query, we are trying to first create the stored procedure with the name ‘GetCustomerInfo’. We then provide it with a single input parameter called @CutomerAge. The stored procedure then selects all records from the ‘CUSTOMERS’ table where the CutomerAge matches the input parameter.
CREATE PROCEDURE GetCustomerInfo @CutomerAge INT AS BEGIN SELECT * FROM CUSTOMERS WHERE AGE = @CutomerAge END
Output
This would produce the following result −
Commands completed successfully.
Verification
To verify the changes, once we have created the stored procedure, we can test it by executing it with different input parameters as shown in the query below −
EXEC GetCustomerInfo @CutomerAge = 25
This will return all columns from the CUSTOMERS table where the cutomer’s age is 25.
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 2 | Khilan | 25 | Delhi | 1500.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | +----+----------+-----+-----------+----------+
Stored Procedure Parameter Types
Stored procedures in a database system can have different types of parameters, which are placeholders for values that will be passed to the stored procedure when it is executed. Following are the different types of stored procedure parameters in SQL −
S.No. | Parameter & Description |
---|---|
1 | Input parameters These parameters are used to pass values from the calling program or user to the stored procedure. |
2 | Output parameters These parameters are used to return values from the stored procedure to the calling program or user. |
3 | Input/Output parameters These parameters allow a stored procedure to accept input values and return output values. |
4 | Table-valued parameters These parameters are used to pass a table variable as a parameter to a stored procedure. |
5 | Default parameters These parameters are used to specify a default value that will be used if no value is passed for the parameter. |
6 | Cursor parameters These parameters are used to pass a cursor to a stored procedure. |
7 | Output XML parameters These parameters are used to return XML data from a stored procedure. |
Now, let us take a look at some of the most common types of stored procedure parameters in SQL −
Procedure with IN parameter
The IN parameter is the default parameter that will receive input value from the program.
We can pass the values as arguments when the stored procedure is being executed. These values are read-only, which means they cannot be modified by the stored procedure.
Example
In the following query we are trying to create a stored procedure that takes a customer’s ID as an input parameter and returns that customer’s salary.
The procedure body simply performs a SELECT statement to retrieve the "Salary" column from the "CUSTOMERS" table, where the "CustomerID" matches the input parameter.
CREATE PROCEDURE GetCustomerSalary @CustomerID INT AS BEGIN SELECT SALARY FROM CUSTOMERS WHERE ID = @CustomerID END
Output
This would produce the following result −
Commands completed successfully.
Verification
To execute the stored procedure and pass in a value for the "@CustomerID" parameter, we will use the EXEC command as given below −
EXEC GetCustomerSalary @CustomerID = 6
This will return the salary for the customer with an ID of 6, assuming there is a corresponding row in the "Customers" table −
+----------+ | SALARY | +----------+ | 4500.00 | +----------+
Procedure with OUT parameter
The OUT parameter sends output value to the program. It allows us to return a value or set of values to the calling program.
Note that when using an OUT parameter, we must specify the keyword "OUT" after the parameter name when passing it to the stored procedure. This tells SQL Server that the parameter is an output parameter and should be assigned a value by the stored procedure.
Example
In the following query we are trying to create a stored procedure that takes the customer’s ID as an input parameter and returns that customer’s salary using an output parameter "@Salary" which holds the salary value returned by the stored procedure.
The procedure body performs a SELECT statement to get the "Salary" column from the "CUSTOMERS" table, where the "ID" matches the input parameter. We use the the assignment operator "=" to assign the returned value to our output parameter "@Salary".
CREATE PROCEDURE GetCustomerSalary @CustomerID INT, @Salary DECIMAL(18,2) OUT AS BEGIN SELECT @Salary = SALARY FROM CUSTOMERS WHERE ID = @CustomerID END
Output
This would produce the following result −
Commands completed successfully.
Verification
Here, we first declare a variable "@CustSalary" of the same datatype as the output parameter "@Salary". We then execute the stored procedure using the EXEC command, passing in the "@CustomerID " parameter and the "@Salary" parameter as an output parameter. Finally, we SELECT the value of the "@CustSalary" variable to display the customer’s salary in the result set.
DECLARE @CustSalary DECIMAL(18, 2) EXEC GetCustomerSalary @CustomerID = 4, @Salary = @CustSalary OUT SELECT @CustSalary AS 'Customer Salary'
This will return the output as shown below −
+-------------------+ | Customer Salary | +-------------------+ | 6500.00 | +-------------------+
Procedure with INOUT parameter
The INOUT parameter is a combination of an IN parameter and an OUT parameter, and it allows us to both pass data into the stored procedure and receive data from the stored procedure.
To declare an INOUT parameter in a stored procedure, we need to use the OUTPUT keyword before the parameter name.
Example
In the following query, we provide two INOUT parameters to the stored procedure: cust_id and salary. The @salary parameter is specified as an OUTPUT parameter, which allows it to be used as both an input and an output parameter.
The stored procedure first retrieves the current salary of the customer from the database using the cust_id parameter. It then increases the salary by 10% and updates the customer’s salary in the database using the cust_id parameter.
CREATE PROCEDURE increaseSalary @cust_id INT, @salary DECIMAL(18, 2) OUTPUT AS BEGIN -- get the current salary of the customer SELECT @salary = SALARY FROM CUSTOMERS WHERE ID = @cust_id; -- increase the salary by 10% SET @salary = @salary * 1.1; -- update the cutomer's salary in the database UPDATE CUSTOMERS SET SALARY = @salary WHERE ID = @cust_id; END;
Output
This would produce the following result −
Commands completed successfully.
Verification
Here we declare and initialize the @cust_id and @salary variables with the values of the Customer ID and salary we want to update. We then call the ‘increaseSalary’ stored procedure, passing in the variables as parameters. The @salary parameter is specified as an OUTPUT parameter, which allows it to be updated within the stored procedure. Finally, we retrieve the updated value of the @salary variable using a SELECT statement.
DECLARE @cust_id INT; DECLARE @salary DECIMAL(18, 2); SET @cust_id = 7; SET @salary = 50000.00; EXEC increaseSalary @cust_id, @salary OUTPUT; SELECT @salary AS 'Customer Salary'
This will return the output as shown below −
+-------------------+ | Customer Salary | +-------------------+ | 11000.00 | +-------------------+
How To Rename a Stored Procedure
To rename a stored procedure in SQL, we use the built-in system stored procedure called sp_rename.
Syntax
Following is the basic syntax to rename a stored procedure in SQL −
sp_rename 'old_procedure_name', 'new_procedure_name';
Example
In the following query we are trying to rename the existing stored procedure ‘GetCustomerSalary’ to ‘newProcedure’−
sp_rename 'GetCustomerSalary', 'newProcedure';
Output
After executing the above query, the 'GetCustomerSalary' stored procedure will be renamed to ‘newProcedure’.
Caution: Changing any part of an object name could break scripts and stored procedures.
Note − Note that if the stored procedure is referenced by other objects such as views or other stored procedures, we need to update those references manually to reflect the new name of the stored procedure. Additionally, renaming a stored procedure may impact any scripts or applications that rely on the old name, so it's a good idea to test our changes thoroughly before deploying them to production.
How To Modify a Stored Procedure
To modify an existing stored procedure in SQL, we use the ALTER PROCEDURE statement. We can add or remove parameters using ALTER PROCEDURE statement.
Note that when we modify a stored procedure, any dependent objects or code that references to it will also need to be modified accordingly.
Syntax
Following is the basic syntax to modify a stored procedure in SQL −
ALTER PROCEDURE procedure_name AS BEGIN -- New procedure code goes here END
Example
Let's say we have a stored procedure called ‘GetCustomerSalary’ that takes in one parameter called @Customer_ID and returns the details of the customer with that ID as shown below −
-- Original stored procedure CREATE PROCEDURE GetCustomerSalary @CustomerID INT AS BEGIN SELECT * FROM CUSTOMERS WHERE ID = @CustomerID END
Following is the output of the above query −
Commands completed successfully.
Now, we are trying to modify the ‘GetCustomerSalary’ stored procedure by adding a new parameter called @CustomerName of type VARCHAR(20). We then modify the SELECT statement to filter on both ‘ID’ and ‘NAME’.
ALTER PROCEDURE GetCustomerSalary @CustomerID INT, @CustomerName VARCHAR(20) AS BEGIN SELECT * FROM CUSTOMERS WHERE ID = @CustomerID AND NAME = @CustomerName END
Output
The result produced is as follows −
Commands completed successfully.How To Delete a Stored Procedure
To delete a stored procedure in SQL, we use the DROP PROCEDURE statement.
Note that dropping a stored procedure will permanently delete it, so make sure that we really want to delete it before executing the DROP PROCEDURE statement. Additionally, dropping a stored procedure may impact any scripts or applications that rely on the stored procedure, so it's a good idea to test our changes thoroughly before deploying them to production.
Syntax
Following is the basic syntax to delete a stored procedure in SQL −
DROP PROCEDURE [IF EXISTS] procedure_name;
Example
DROP PROCEDURE IF EXISTS GetCustomerSalary;
Output
The result produced is as follows −
Commands completed successfully.
Advantages of Stored Procedure
Following are the advantages of stored procedures −
Improved Performance − Stored procedures are pre-compiled and stored on the server, so they can be executed more quickly than SQL statements that are sent from client applications.
Code Reuse − Stored procedures can be called from different client applications, which means that the same code can be reused across different applications. This reduces development time and maintenance costs.
Reduced Network Traffic − Because stored procedures are executed on the server, only the results are returned to the client, which reduces network traffic and improves application performance.
Better Security − Stored procedures can be used to enforce security rules and prevent unauthorized access to sensitive data. They can also limit the actions that can be performed by users, making it easier to maintain data integrity and consistency.
Simplified Maintenance − By storing SQL code in a single location, it becomes easier to maintain and update the code. This makes it easier to fix bugs, add new functionality, and optimize performance.
Drawbacks of Stored Procedure
Following are the disadvantages of stored procedures −
Increased Overhead − Stored procedures can consume more server resources than simple SQL statements, particularly when they are used frequently or for complex operations.
Limited Portability − Stored procedures are often specific to a particular database management system (DBMS), which means they may not be easily portable to other DBMSs.
Debugging Challenges − Debugging stored procedures can be more challenging than debugging simple SQL statements, particularly when there are multiple layers of code involved.
Security Risks − If stored procedures are not written correctly, they can pose a security risk, particularly if they are used to access sensitive data or to perform actions that could compromise the integrity of the database.