Skip to main content

Command Palette

Search for a command to run...

SQL - Stored Procedures vs Functions

Exploring stored procedures and functions, as well as their respective functionalities.

Published
3 min read
SQL - Stored Procedures vs Functions
F

Principal Technical Consultant at GeekyAnts.

Bootstrapping our own Data Centre services.

I lead the development and management of innovative software products and frameworks at GeekyAnts, leveraging a wide range of technologies including OpenStack, Postgres, MySQL, GraphQL, Docker, Redis, API Gateway, Dapr, NodeJS, NextJS, and Laravel (PHP).

With over 9 years of hands-on experience, I specialize in agile software development, CI/CD implementation, security, scaling, design, architecture, and cloud infrastructure. My expertise extends to Metal as a Service (MaaS), Unattended OS Installation, OpenStack Cloud, Data Centre Automation & Management, and proficiency in utilizing tools like OpenNebula, Firecracker, FirecrackerContainerD, Qemu, and OpenVSwitch.

I guide and mentor a team of engineers, ensuring we meet our goals while fostering strong relationships with internal and external stakeholders. I contribute to various open-source projects on GitHub and share industry and technology insights on my blog at blog.faizahmed.in.

I hold an Engineer's Degree in Computer Science and Engineering from Raj Kumar Goel Engineering College and have multiple relevant certifications showcased on my LinkedIn skill badges.

Introduction

In this article, we're going to discuss the differences between stored procedures and functions. Before we begin comparing stored procedures with functions in SQL, I'd like to explain them briefly.

Stored Procedures

A stored procedure is a collection of SQL statements that are stored in a database to perform some actions (business logic) or any database-related task.

Below, I've created a stored procedure with the name GetUsers that simply queries a USERS table and retrieves all users.

DELIMITER $$

CREATE PROCEDURE `GetUsers`()

BEGIN
  SELECT * FROM USERS;
END$$

DELIMITER;

Functions

Functions may take arguments, perform calculations or operations, and return the result.

Mainly there are two types of functions:

  1. Built-in or System functions
  2. User Defined functions

Built-in Functions

There are a lot of built-in functions available in the databases, such as count, aggregate, date, string, and so on. Some of them are listed below, along with their definitions.

MIN()     -- Returns the minimum value

MAX()     -- Returns the maximum value

COUNT()   -- Returns the count value

SUM()     -- Returns the summation value

AVG()     -- Returns the average value

User Defined Functions

Below, I've created a user-defined function with the name GetUserName which takes UserID as a parameter and returns the user's name from a USERS table.

DELIMITER $$

CREATE FUNCTION `GetUsername`(UserID int)
RETURNS varchar(32)

DETERMINISTIC

BEGIN
  DECLARE Username varchar(32);
  SELECT NAME INTO Username FROM USERS WHERE ID = UserID;
  RETURN Username;
END$$

DELIMITER;

Comparing the two...

After gaining a basic understanding of SQL stored procedures and functions, It's time to see how the two stack up in terms of the important functionalities listed below.

Calling

Stored Procedures can call functions, but functions cannot call stored procedures.

CALL GetUsers();  -- Calling a store procedure

Functions can be called inline from SELECT, UPDATE, DELETE, and INSERT queries, but stored procedures cannot.

SELECT GetUsername(12);  -- Calling a user defined function with a parameter

Removing

The methods for removing stored procedures and user-defined functions are listed below.

DROP PROCEDURE `GetUsers`;  -- Removing a stored procedure
DROP FUNCTION `GetUsername`;  -- Removing a user defined function

Return Values

Stored procedures may return multiple values but functions only return a single scalar value or a table.

Functions always return a value, whereas stored procedures may or may not.

Parameters

Stored procedures support two types of parameters: Input and Output.

Functions on the other hand only support input parameters.

Restrictions

Stored procedures can modify the database by using ALTER, UPDATE, DELETE, etc commands.

Since functions can only use SELECT statements, they cannot change the database state.

Transactions

Stored procedures allow the use of transactions, and we can write logic to roll back/commit transactions to init.

Functions cannot make use of transactions.

Exception Handling

Stored procedures support try-catch blocks and exception handling can also be written in init.

Functions, on the other hand, do not support init.

Summary

After reading this article, you will gain a good understanding of stored procedures and functions.

In addition, an example-based approach to using these highly powerful techniques is offered, along with information on when and where to apply them.


About Me 👨‍💻

I'm Faiz A. Farooqui. Software Engineer from Bengaluru, India. Find out more about me @ faizahmed.in