🗄️ Databases

Stored Procedure

Stored Procedure

Executable code stored in the database. Business logic.

Detailed Explanation

A Stored Procedure is a collection of SQL statements and programming logic that is stored and executed on a database server. Once compiled, it is reused, so there is no overhead of parsing the SQL and building an execution plan every time.

Its main advantages are reduced network traffic (complex operations performed with a single call), code reusability, and enhanced security (granting permissions on the procedure instead of direct table access). In addition, Transaction handling and error handling can be implemented at the DB level.

On the other hand, it has drawbacks: version control is difficult, application logic becomes dependent on the DB, and debugging is inconvenient. Its use has declined recently with the emergence of ORMs and microservice architecture, but it is still useful for batch processing and complex data transformations.

Code Example

-- MySQL 스토어드 프로시저 생성
DELIMITER //
CREATE PROCEDURE GetEmployeesByDept(
    IN dept_id INT,
    OUT employee_count INT
)
BEGIN
    -- 직원 목록 조회
    SELECT id, name, salary
    FROM employees
    WHERE department_id = dept_id;

    -- 직원 수 반환
    SELECT COUNT(*) INTO employee_count
    FROM employees
    WHERE department_id = dept_id;
END //
DELIMITER ;

-- 프로시저 호출
CALL GetEmployeesByDept(10, @count);
SELECT @count AS total_employees;

-- 조건문과 반복문 포함 프로시저
DELIMITER //
CREATE PROCEDURE UpdateSalaries()
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE emp_id INT;
    DECLARE emp_salary DECIMAL(10,2);
    DECLARE cur CURSOR FOR SELECT id, salary FROM employees;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    START TRANSACTION;

    OPEN cur;
    read_loop: LOOP
        FETCH cur INTO emp_id, emp_salary;
        IF done THEN
            LEAVE read_loop;
        END IF;

        IF emp_salary < 3000000 THEN
            UPDATE employees SET salary = salary * 1.1 WHERE id = emp_id;
        END IF;
    END LOOP;
    CLOSE cur;

    COMMIT;
END //
DELIMITER ;

Practical Conversation Example

PM: The month-end settlement batch takes more than 4 hours. Is there any way to improve it?

DBA: Right now the application sends a Query for each record. If we move to a Stored Procedure, network round trips will be reduced and it should get faster.

Backend developer: But isn't version control difficult for procedures?

DBA: That's right. You can include the procedure DDL in Git and manage it with a migration tool.

Interviewer: Please explain the advantages and disadvantages of a Stored Procedure.

Candidate: The advantages are improved performance through compiling once and reusing, reduced network traffic, and fine-grained permission management. The disadvantages are difficulty with version control and debugging, DB vendor dependency, and fragmentation of application logic.

Interviewer: When is it appropriate to use a procedure?

Candidate: It is useful for bulk data batch processing, complex Transactions, and when direct table access must be blocked for security reasons.

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Senior: This procedure has no error handling. What happens if it fails?

Junior: Oh, an error would just occur.

Senior: Add exception handling with DECLARE HANDLER, and make it ROLLBACK on error. If it fails midway in production, data integrity breaks.

Cautions

Related Terms

Learn More