Introduction
Functions let you save a set of instructions in the database to reuse later. This helps avoid repeating the same code.
Jump into concepts and practice - no test required
Functions let you save a set of instructions in the database to reuse later. This helps avoid repeating the same code.
CREATE [OR REPLACE] FUNCTION function_name (parameters) RETURNS return_type AS $$ BEGIN -- function body RETURN value; END; $$ LANGUAGE plpgsql;
CREATE OR REPLACE lets you update the function if it exists.
The function body goes between BEGIN and END;.
CREATE FUNCTION add_two_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION greet(name text) RETURNS text AS $$ BEGIN RETURN 'Hello, ' || name || '!'; END; $$ LANGUAGE plpgsql;
CREATE FUNCTION get_current_year() RETURNS integer AS $$ BEGIN RETURN EXTRACT(YEAR FROM CURRENT_DATE)::integer; END; $$ LANGUAGE plpgsql;
This creates a function that multiplies a number by three, then calls it with 5.
CREATE OR REPLACE FUNCTION multiply_by_three(num integer) RETURNS integer AS $$ BEGIN RETURN num * 3; END; $$ LANGUAGE plpgsql; SELECT multiply_by_three(5);
Always specify the language (usually plpgsql) at the end.
Use CREATE OR REPLACE to update functions without dropping them first.
Functions can take zero or more parameters and must specify a return type.
Functions store reusable code inside the database.
Use CREATE FUNCTION with parameters, return type, and body.
Call functions like normal queries to get results.
CREATE FUNCTION statement in PostgreSQL?CREATE FUNCTION doesSELECT add_one(5);?
CREATE FUNCTION add_one(x integer) RETURNS integer AS $$ BEGIN RETURN x + 1; END; $$ LANGUAGE plpgsql;
CREATE FUNCTION multiply_by_two(x integer) RETURNS integer AS $$ BEGIN RETURN x * 2 END; $$ LANGUAGE plpgsql;
x * 2, causing a syntax error.concat_names that takes two text parameters and returns their concatenation separated by a space. Which of the following is the correct function definition?