✏️ Explanatory Question

What is the difference between a stored procedure and a function?

👁 8 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

68

What is the difference between a stored procedure and a function?

Level: Advanced — A very common question; the key differences lie in return values and where they can be used.

Both are stored programs containing reusable SQL logic, but they differ in how they return values and where they can be called.

  • Stored Procedure: Performs an action. Can return zero, one, or many values (via OUT parameters or result sets). Called with CALL. Can perform DML and manage transactions.
  • Function (UDF): Computes and returns a single value. Called inside SQL expressions (like SELECT, WHERE). Must have a RETURNS clause.
The key distinction: A function must return exactly one value and can be embedded in a query (SELECT fn(x)), while a procedure is called separately with CALL and is used for performing actions, not for use inside expressions.

Side-by-Side Comparison

Feature Stored Procedure Function
Return value Zero, one, or many (OUT) Exactly one (RETURNS)
Called with CALL Inside SQL expressions
Use in SELECT/WHERE? No Yes
Parameters IN, OUT, INOUT IN only
DML (INSERT/UPDATE) Allowed Restricted
Transactions Can manage Cannot manage
Try/Catch (handlers) Allowed Allowed (limited)

Quick Example — Function vs Procedure

-- FUNCTION: returns a single value, usable in a query
DELIMITER $$
CREATE FUNCTION GetAnnualSalary(p_monthly DECIMAL(10,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
    RETURN p_monthly * 12;
END $$
DELIMITER ;

-- Use it directly inside a SELECT
SELECT name, GetAnnualSalary(salary) AS yearly FROM employees;

-- PROCEDURE: performs an action, called with CALL
DELIMITER $$
CREATE PROCEDURE GiveRaise(IN p_id INT, IN p_amount DECIMAL(10,2))
BEGIN
    UPDATE employees SET salary = salary + p_amount WHERE emp_id = p_id;
END $$
DELIMITER ;

CALL GiveRaise(1, 5000);
Note on DETERMINISTIC: A function should be marked DETERMINISTIC if it always returns the same output for the same input — this helps the optimizer and is often required depending on binary logging settings.
Interviewer tip: The one-liner they want — "A function returns a single value and can be used inside SQL expressions, while a stored procedure performs actions, can return multiple values via OUT parameters, and is invoked with CALL."