✏️ Explanatory Question

What is a stored procedure and what are its advantages?

👁 6 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Section 9: Stored Programs & Objects

67

What is a stored procedure and what are its advantages?

Level: Advanced — Stored procedures bundle reusable business logic directly inside the database.

A stored procedure is a precompiled set of SQL statements stored in the database under a name, which can be executed (called) whenever needed. It can accept parameters, contain control-flow logic (IF, loops), and perform multiple operations in one call.

Key point: Stored procedures support three parameter modes — IN (input, default), OUT (output/return), and INOUT (both). This lets them receive data and send results back to the caller.

Advantages of Stored Procedures

  • Reusability: Write once, call many times from different applications.
  • Performance: Precompiled and cached, reducing parsing overhead.
  • Reduced network traffic: One call runs many statements on the server side.
  • Security: Grant execute rights without exposing underlying tables.
  • Maintainability: Business logic centralized in one place.

Parameter Modes

Mode Direction Purpose
IN Input (default) Pass a value into the procedure
OUT Output Return a value to the caller
INOUT Both Pass in and return modified value

Prerequisite

When writing a procedure with multiple statements, you must change the statement delimiter (e.g., to $$) so MySQL doesn't treat the inner semicolons as the end of the whole procedure. Reset it back to ; afterward.

Quick Example

-- Change delimiter so inner ; are not treated as end of procedure
DELIMITER $$

CREATE PROCEDURE GetEmployeesByDept(IN p_dept_id INT)
BEGIN
    SELECT emp_id, name, salary
    FROM employees
    WHERE dept_id = p_dept_id;
END $$

DELIMITER ;

-- Call the procedure
CALL GetEmployeesByDept(10);

-- Procedure with an OUT parameter
DELIMITER $$
CREATE PROCEDURE CountEmployees(IN p_dept INT, OUT p_total INT)
BEGIN
    SELECT COUNT(*) INTO p_total
    FROM employees WHERE dept_id = p_dept;
END $$
DELIMITER ;

CALL CountEmployees(10, @total);
SELECT @total;   -- retrieve the returned value
Interviewer tip: The one-liner they want — "A stored procedure is a named, precompiled set of SQL statements that accepts IN/OUT/INOUT parameters. It improves reusability, performance, security, and reduces network traffic by running logic server-side."