DEV Community

Cover image for Exploring the Similarities Between SQL Stored Procedures and Python Functions
Njeri Kimaru
Njeri Kimaru

Posted on

Exploring the Similarities Between SQL Stored Procedures and Python Functions

DEFINITIONS

Stored Procedure (SQL)

A stored procedure is a group of SQL statements that are saved (stored) in the database and can be executed whenever needed.

It is used to perform tasks like inserting, updating, or retrieving data, and can include logic such as conditions (IF) and loops (WHILE). Stored procedures can also accept input and return output.

sql create procedures GetCustomerOrders(IN customer_id INT)
BEGIN
SELECT order_id, customer_id, item
FROM orders
WHERE customer_id = cust_id;
END;


Python functions (Python)

A Python function is a reusable block of Python code that performs a specific task when called. It usually accepts input values (called parameters), processes them, and can return an output (result).

Functions help break down programs into smaller parts, making code easier to read, test, and reuse.

python def get_customer_orders(customer_id, orders):
customer_orders = []
for order in orders:
if order["customer_id"] == customer_id:
customer_orders.append(order)
return customer_orders

Sample data

orders_list = [
{"order_id": 1, "customer_id": 101, "item": "Laptop"},
{"order_id": 2, "customer_id": 102, "item": "Headphones"},
{"order_id": 3, "customer_id": 101, "item": "Mouse"}

Example usage

result = get_customer_orders(101, orders_list)
print(result)


SIMILARITIES

  • stored procedure in SQL and a function in Python are similar in many ways, even though they are used in different programming environments.
  1. Both stored procedures and Python functions are designed to group a set of instructions or operations together into a single reusable unit. This makes code easier to manage, understand, and maintain.

  2. They both can accept parameters. A stored procedure can receive input values (and even return output values), just like a Python function can take arguments to work with different data without changing the code inside.

  3. Both allow the use of control flow logic, such as IF conditions, WHILE loops, and other statements to control how the code runs based on different conditions.

  4. They are both used to encapsulate logic, which means hiding the internal steps and exposing only the functionality. This helps developers reuse the logic multiple times in different parts of a program or application without repeating code.

  5. Both stored procedures and Python functions help with modularity — breaking down large programs or processes into smaller, manageable blocks — and they promote the DRY principle (Don’t Repeat Yourself), which encourages code reuse.

Top comments (0)