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.