Sobes.tech
Junior — Middle

Can you explain what a procedure in SQL is and how it is used?

sobes.tech AI

Answer from AI

A procedure in SQL is a named block of code that performs a specific set of operations on a database. It can accept parameters, execute queries, modify data, and return results.

Procedures are used for:

  • Automating frequently repeated operations.
  • Encapsulating business logic on the database side.
  • Improving performance by executing code directly in the DBMS.

Example of creating a procedure in SQL:

CREATE PROCEDURE GetUserById(IN userId INT)
BEGIN
    SELECT * FROM users WHERE id = userId;
END;

In Python, to call such a procedure, you can use a database library like pymysql or psycopg2:

cursor.callproc('GetUserById', [123])
result = cursor.fetchall()

Thus, a procedure is a way to group and reuse SQL code.