What is the difference between a function and a stored procedure in MySQL?
Answer
Stored Function: returns exactly one value; can be called inside SQL expressions (SELECT, WHERE, etc.); declared with RETURNS datatype and must have a RETURN statement; cannot include transaction control (COMMIT/ROLLBACK); cannot call stored procedures that modify data (in most contexts); used for encapsulating computations: CREATE FUNCTION get_age(dob DATE) RETURNS INT DETERMINISTIC RETURN TIMESTAMPDIFF(YEAR, dob, CURDATE()); — call: SELECT name, get_age(birth_date) FROM users;. Stored Procedure: does not return a value via RETURN (uses OUT parameters or result sets); called with CALL, not inside expressions; can execute any SQL including DDL, transactions, and dynamic SQL (PREPARE/EXECUTE); can return multiple result sets; better for complex business workflows. Key differences: functions can be used in SELECT/WHERE/HAVING; procedures cannot. Procedures can modify data and manage transactions freely; functions have restrictions (DETERMINISTIC declaration required for replication safety). In practice: use functions for reusable computations used in queries; use procedures for complex multi-step workflows, batch operations, or when you need to return multiple result sets. Both support IN/OUT parameters, though functions primarily use IN.
Previous
What are generated columns in MySQL?
Next
How does MySQL handle full-text indexing vs regular B-tree indexing for large text searches?
More MySQL / SQL Questions
View all →- Advanced What is the difference between B-tree and Hash indexes in MySQL?
- Advanced What is MVCC (Multi-Version Concurrency Control) in MySQL?
- Advanced What is the InnoDB Buffer Pool and how does it work?
- Advanced What is deadlock in MySQL and how do you prevent it?
- Advanced What is the query execution plan and how does the MySQL optimizer work?