Skip to main content

How do you create a function?

A function in SQL is created with the CREATE FUNCTION command.

General form:

sql
CREATE FUNCTION function_name(parameters) RETURNS data_type AS BEGIN -- function body RETURN value; END;

Example

sql
CREATE FUNCTION get_full_name(first_name VARCHAR(50), last_name VARCHAR(50)) RETURNS VARCHAR(100) AS BEGIN RETURN CONCAT(first_name, ' ', last_name); END;

Now you can use it in queries:

sql
SELECT get_full_name('Ivan', 'Petrov');

Note: the syntax can vary slightly between DBMSes (e.g. PostgreSQL, MySQL, SQL Server), but the logic is the same everywhere - a function takes arguments, runs a computation, and returns a result.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.