SQL FUNCTION (more formally the CREATE FUNCTION statement) lets you define a named, parameter-driven routine that can be called inside queries just like a built-in function. A function must return exactly one value (scalar, table, or composite depending on the dialect) and is typically used to encapsulate business logic, complex expressions, or repeated calculations.Unlike procedures, functions can be embedded in SELECT, WHERE, JOIN, and ORDER BY clauses because they are expected to be free of side-effects. Many engines enforce this by restricting data-modifying commands inside a function or by requiring the function to be declared as VOLATILE, STABLE, or IMMUTABLE (PostgreSQL) or by using the CONTAINS SQL / READS SQL DATA modifiers (MySQL, SQL-99).Functions are stored in the database catalog, versioned alongside schema changes, and executed on the server, which improves performance and security compared with shipping raw SQL to the client. You can overload functions by argument list, set default values for parameters, and call them from other functions or procedures.Caveats:- Function bodies are parsed only at creation time; syntax errors show up then, not at call time.- Some engines prevent data modification within a function, others allow it but mark the function as non-deterministic which can disable certain optimizations.- Dropping or replacing a function that is referenced by views or other routines can break dependent objects.
function_name
(identifier) - Name of the function to create.mode
(keyword) - Optional IN, OUT, or INOUT direction of a parameter (dialect specific).param_name
(identifier) - Name of an input or output parameter.data_type
(type) - SQL data type of the parameter.return_data_type
(type) - SQL data type of the value returned by the function.language_name
(identifier) - Implementation language (SQL, PLPGSQL, TSQL, JavaScript, etc.).DETERMINISTIC flag
- Declares whether the function always returns the same output for the same inputs.SQL data access modifiers
- Declare whether the function reads or writes data.SECURITY DEFINER/INVOKER
- Defines whether the function runs with the privileges of its creator or caller.CREATE PROCEDURE, RETURN, DROP FUNCTION, PARAMETERS, TRIGGER, STORED PROCEDURE
SQL:1999
A function must return a value and is intended for use in SELECT or other expressions, while a procedure can return zero or many result sets and is usually executed with CALL/EXEC for side effects.
In some engines yes, but PostgreSQL requires LANGUAGE. Omitting it defaults to LANGUAGE SQL, which may not support procedural constructs like IF or LOOP.
Most databases support CREATE OR REPLACE FUNCTION. If not, you must DROP FUNCTION first and then CREATE FUNCTION again.
Well-written deterministic functions are often inlined or cached by the optimizer, so performance impact is minimal. Non-deterministic or I/O heavy functions can slow queries.