Skip to content
We areTOP 1%

What is a stored procedure, and how is it different from a function?

MediumConceptDBMS Fundamentals
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

A stored procedure is a named set of SQL statements saved inside the database and run with a single call, such as CALL give_raise(10). It can take parameters, use logic such as IF and loops, and run several statements as one unit.

  • Benefits: less network traffic (one call instead of many statements), reusable logic, and permission can be granted on the procedure instead of on the tables.
  • A function must return a value and can be used inside a query, as in SELECT tax(price) FROM items. A procedure is called on its own and returns results through output parameters or result sets.
  • Procedures can usually control transactions with COMMIT and ROLLBACK; functions cannot, and SQL Server does not allow a function to modify tables at all.

Example: In MySQL:

CREATE PROCEDURE give_raise(IN pct INT)
  UPDATE employees SET salary = salary * (1 + pct / 100);

CALL give_raise(10);   -- every salary rises by 10 percent

More in DBMS Fundamentals

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account