SQL Stored Procedures
Stored procedures in SQL are an essential tool for automating and simplifying repetitive database tasks. They allow you to create blocks of code that can be run as needed, making working with data more efficient and convenient. Today, we’ll explore what procedures are in SQL, why they’re needed, and how to create them.
What is a stored procedure in SQL?
A stored procedure in SQL is a set of SQL commands stored on the database server and executed on request. It is created once and stored on the server, allowing it to be called multiple times, ensuring code reuse and improving database performance.
Why are stored procedures useful?
- Performance Optimization: Stored procedures are stored and executed directly on the database side, reducing the likelihood of performance delays.
- Simplify logic: By supporting parameters and SQL constructs such as loops and conditions, procedures allow you to organize complex data processing by reducing the work to a single command call.
- Code reuse: A procedure created once can be called multiple times on different sets of data, reducing code duplication and making the application more robust.
- Performance improvements: Procedures are compiled when created, so they don’t need to be recompiled each time they are called, which speeds up execution.
What is the difference between a stored procedure and a function?
Stored procedures in SQL can sometimes be confused with functions—both are used to execute logic and process data on the server side. However, they have significant differences in purpose, use, and functionality.
- Return value: A procedure can return one or more values through
OUTparameters, or return nothing. A function always returns a single value. - Usage in queries: The function can be used in
SELECT,WHEREand other SQL queries. The procedure cannot be used in queries; it is called separately. - Modifying data: A procedure can modify data (e.g., perform
INSERT,UPDATE,DELETE). A function typically does not modify data in tables. - Transaction Management: Transactions can be managed in a procedure (
COMMIT,ROLLBACK). This is not supported by the function. - Basic purpose: A procedure performs tasks and operations on data, while a function calculates and returns a result.
General syntax of procedures
It’s important to note that different DBMSs use their own syntactic features and extensions when working with SQL procedures. We’ll discuss some of these below, but for now, let’s look at the general procedure syntax.
CREATE PROCEDURE procedure_name (parameter1 data_type, parameter2 data_type, ...)
BEGIN
-- Procedure body END;Main components :
- CREATE PROCEDURE: command to create a procedure.
- procedure_name: The name of the procedure that will be used later to run it.
- Parameters: Most DBMSs allow you to specify input and output parameters to pass data to a procedure and retrieve a result. Parameters have a direction (
IN,OUT,INOUT) and a data type. - Procedure body: the block where the SQL instructions and logic for the procedure are written. It may contain various functions, operators, conditional statements, and loops.
How to create a procedure in SQL
Access rights
When creating a procedure in SQL, access rights play a crucial role in ensuring data security. Most DBMSs have rights management mechanisms that allow you to restrict users’ ability to create, modify, execute, and delete procedures.
Basic access rights when creating and working with procedures:
- Permissions to create a procedure. For example, in MySQL this permission is
CREATE ROUTINE, in PostgreSQL it isCREATE, and in Oracle it isCREATE PROCEDURE. - Execute procedure permissions (e.g.
EXECUTE) allow specific users or groups to execute a procedure. These permissions can be assigned using the command.GRANT EXECUTE ON procedure_name TO user_name;. - Permissions to modify and delete the procedure. The user needs editing privileges, such as
ALTERorDROP. - Data access permissions in the procedure body. When a procedure interacts with tables and other database objects, it must be ensured that it has the permissions to perform operations on these objects (e.g.,
SELECT,INSERT)UPDATE.
An example of creating a procedure in MySQL
In MySQL, procedures are created using the commandCREATE PROCEDURE, followed by the procedure name and a list of parameters (if any). This is followed by the procedure body, enclosed in a block. BEGIN ... END.
DELIMITER //
CREATE PROCEDURE procedure_name (parameters) BEGIN -- SQL commands ... END //
DELIMITER ;
DELIMITER is used to tell MySQL that the command termination character in this context will be //, not ;, since multiple statements separated by are often used within a procedure ;.
Let’s say we need to create a procedure that returns a list of all employees over a certain age from a table. employees.
DELIMITER //
CREATE PROCEDURE GetEmployeesByAge (IN min_age INT)
BEGIN
SELECT * FROM employees WHERE age > min_age;
END //
DELIMITER ;IN min_age INT – An input parameter (see below) that accepts the minimum age to filter the data.
Inside the procedure, a query is executed that returns all employees whose age is greater than the value passed through the parameter.
Example of creating a procedure in PostgreSQL
In PostgreSQL, procedures are created using the command CREATE PROCEDURE, but they require a language specification (most often plpgsql).
CREATE PROCEDUREprocedure_name (parameters) LANGUAGE plpgsql AS $ BEGIN -- SQL commands ... END; $;In PostgreSQL, you can create more complex procedures, including working with variables and execution logic. Let’s look at an example procedure that counts the number of orders for a specific customer in the orders table.
CREATE PROCEDURE CountCustomerOrders (IN customer_id INT)
LANGUAGE plpgsql
AS $
DECLARE
total_orders INT;BEGIN
SELECT COUNT(*) INTO total_orders FROM orders WHERE orders.customer_id = customer_id;
RAISE NOTICE 'Total Orders: %', total_orders;
END;
$;- DECLARE is a variable declaration block where we declare a variable
total_ordersto store the result. - RAISE NOTICE — output a message to the log (analogous to data output).
Input and output parameters
These are the key elements in stored procedures that allow you to pass data into the procedure and return results from it.
Input parameters (IN) allow you to pass values into a procedure for use in its execution logic.
For example, let’s create a procedure that takes a student ID and the number of extra points to add to the current points.
CREATE PROCEDURE add_bonus_points(student_id INT, bonus_points INT)
AS $
BEGIN
-- Add additional points to the student's current points UPDATE students
SET score = score + bonus_points
WHERE id = student_id;
END;
$;In this example:
student_id— input parameter that determines which student to update.bonus_points— an input parameter indicating by how many points to increase the current ones.
Output parameters (OUT) allow a procedure to return values after execution. For example, let’s create a procedure that returns a student’s name based on their ID:
CREATE PROCEDURE get_student_name(student_id INT, OUT student_name VARCHAR(100))
AS $
BEGIN
-- We extract the student's name and write it to the output parameter student_name
SELECT name INTO student_name
FROM students
WHERE id = student_id;
END;
$;In this example:
student_id— input parameter for student search.student_name— output parameter where the student’s name is saved.
INOUT parameters can be either input or output, allowing data to be passed and modified.
Let’s say we have a procedure that increases a student’s score by a certain amount and returns the new score. To do this, we’ll use an INOUT parameter that accepts the original score and returns the updated score.
CREATE PROCEDURE update_student_score(INOUT student_id INT, INOUT current_score INT, IN bonus INT)
AS $
BEGIN
-- Increase the student's score by the specified amount UPDATE students SET score = current_score + bonus WHERE id = student_id; -- Update the current_score value and return it via the INOUT parameter SELECT score INTO current_score
FROM students
WHERE id = student_id;
END;
$;student_id— INOUT parameter that passes the student ID to the procedure and can also be used to return changes (for example, after updating scores).current_score— INOUT parameter that passes the current student score and is updated with new scores during the procedure.bonus— IN parameter that passes the number of points to increase.
Starting the procedure
Running a procedure is the process that begins after it has been called and involves several steps, from passing parameters to executing instructions and returning results.
To run a procedure in SQL, the command is typically used. CALL:
CALLprocedure_name(parameter1, parameter2, ...);Let’s look at starting a procedure using the previous example – the procedure. update_student_score:
-- An example of a procedure call where we pass the student ID, current scores, and bonus CALL update_student_score(1, 50, 10); -- Student ID = 1, current scores = 50, bonus = 10- Passing parameters: We call the procedure
CALL update_student_score(1, 50, 10);by passingstudent_id = 1,current_score = 50, andbonus = 10. - Executing the procedure logic: The procedure finds the student with ID 1 and updates his score by adding
current_scorethe value tobonus. The score becomes 60. - Returning a new value :
current_scoreThe new value 60 is written to the updated variable and returned from the procedure.
Deleting a stored procedure
Dropping a stored procedure is the process of removing the procedure itself from the database. Once deleted, it is no longer available for execution.
In PostgreSQL, MySQL, and SQL Server, the command is used for this purpose. DROP PROCEDURE.
DROP PROCEDURE [IF EXISTS] procedure_name([parameter_types]);IF EXISTS— an optional parameter that allows you to avoid an error if a procedure with the same name does not exist.procedure_name— the name of the procedure to be deleted.parameter_types— an optional list of parameter types (if the procedure is overloaded, then parameters must be specified for correct deletion).
DROP PROCEDURE IF EXISTS update_student_score;
This query will delete the procedure--Changing procedures
Modifying stored procedures in SQL usually requires dropping them and creating new versions, as most DBMSs do not support direct modification.
- In MySQL
DROP PROCEDURE,, is used and then a new version of the procedure is created with the necessary changes. - In PostgreSQL, you can use the command
CREATE OR REPLACE PROCEDUREto avoid dropping the procedure manually. - In SQL Server, to modify an existing procedure, the command is used.
ALTER PROCEDURE.
Conclusion
Stored procedures in SQL are a powerful tool that helps automate tasks and improve database performance. They simplify repetitive operations and make code cleaner and more maintainable. Now that you know the basics of working with stored procedures in SQL, you can use them to improve your database workflow and optimize complex operations!
Explore More IT Terms
#
A
- A Guide to SQL Query Formatting
- A/B testing
- Agile
- Algorithm complexity in 5 minutes
- Algorithms and Data Structures in C#
- An overview of the C # programming language
- An overview of the Python programming language
- Anaconda Python
- Android
- Android App Bundle
- Android SDK
- Angular
- Ansible
- Apache
- Apache Airflow
- Apache Kafka
- Apache Tomcat
- App Store
- AppCode
- Array-based stack
- ArrayList
- ASCII
- ASP.NET
- Assembly Language Lessons
B
C
D
- Data Analytics: applications of data analysis in companies
- Data Engineer - Who is it, what does a data engineer do, and an overview of the profession
- Data modeling: what it is, types, and process steps.
- Data preprocessing: a complete guide for beginners and professionals.
- Data structure
- Data structures
- Defining Aliases
- Defining Arrays
- Deque
- Developing a Website from Scratch
- Digital data: understand the importance of this asset for businesses.
- Doubly linked lists
E
F
H
- Handling errors and exceptions
- How to effectively organize your workflow
- How to Learn Java: Tips for Beginner Developers
- How to Learn PHP: A Beginner's Guide
- How to Use S3 Storage in Kubernetes with CSI
- HTML
- HTML and CSS: Definition, Application, and Operating Principles
- HTML and CSS. Layout from Scratch: What to Learn, Where to Learn, and How Long Will It Take?
- HTML Frame Structure
- HTML Link Formatting
I
- if..else construction
- Inserting an Image
- Interactive Python Tutorial – Learn Programming from Scratch
- Interview Problem: Finding a Deleted Element in O(N)
- Interview Scare: The FizzBuzz Challenge
- Introduction to C++
- Introduction to Machine Learning
- Introduction to programming languages
- IT Specialist Resume (CV)
K
M
O
P
S
- SFML Graphics Library Tutorials
- SQL commands: see what they are, what the main ones are + examples
- SQL Interview Questions and Tasks
- SQL Lessons
- SQL Stored Procedures
- SQL Syntactic Sugar: The COALESCE Function
- Stack
- Start in analytics: Python or R
- Statistical analysis: importance for decision making.
- String formatting in Python
- Swift Lessons
- switch/match construct
T
W
- What are databases, and why do they need DBMS and SQL?
- What do Linux distributions consist of?
- What is .NET and what is it used for?
- What is a GPU in a computer, in simple terms?
- What is Big Data? Introduction, Types, Characteristics, and Examples
- What is Golang and what is it used for?
- What is Haskell and what is it used for?
- What is Kotlin and what is it used for?
- What is Linux? The History of Linux
- What is machine learning, and how does it work?
- What is Power BI: everything about the data analytics software
- What is the C++ programming language?
- What is the OSI Model: A Complete Explanation of the Seven Layers and Their Role in Networking
- Where to start learning the C programming language?
- Which Linux distribution should you choose? A Linux distribution overview
