PostgreSQL Tutorial
Data Types
Querying & Filtering Data
Managing Tables
Modifying Data
Conditionals
Control Flow
Transactions & Constraints
Working with JOINS & Schemas
Roles & Permissions
Working with Sets
Subquery & CTEs
User-defined Functions
Important In-Built Functions
PostgreSQL PL/pgSQL
Variables & Constants
Stored Procedures
Working with Triggers
Working with Views & Indexes
Errors & Exception Handling
In PostgreSQL, you can use the CREATE FUNCTION
statement to define a new function. Functions allow encapsulation of logic that can be reused in various parts of your application or database logic. PostgreSQL supports a variety of procedural languages for function creation, such as PL/pgSQL, PL/Tcl, PL/Perl, and others. However, PL/pgSQL is the most common and is included with the standard PostgreSQL distribution.
Here's how to create a function using the CREATE FUNCTION
statement:
CREATE FUNCTION function_name (parameter_name parameter_data_type,...) RETURNS return_data_type AS $$ -- function body $$ LANGUAGE plpgsql;
Let's create a simple function to add two numbers:
CREATE FUNCTION add_numbers(a INTEGER, b INTEGER) RETURNS INTEGER AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;
To call this function:
SELECT add_numbers(5, 3); -- Returns 8
Parameters: Functions can have zero or more parameters. In the above example, the function add_numbers
has two parameters of type INTEGER
.
Return Type: The RETURNS
clause specifies the data type of the result of the function. It can be a scalar type, a record type, or a reference cursor type.
Function Body: The actual logic of the function is defined in the body. It's enclosed between the $$
delimiters.
Language: The LANGUAGE
clause specifies the language in which the function is implemented. plpgsql
is the language we used in the example, but as mentioned earlier, other procedural languages can also be used.
Volatility Categories: You can specify the function's behavior in terms of its effects on database state:
VOLATILE
(default): The function can have side effects, and its result can vary from one call to another, even with the same arguments.STABLE
: The function cannot modify the database and is guaranteed to return the same results given the same arguments for all rows within a single statement.IMMUTABLE
: The function cannot modify the database and is guaranteed to return the same results given the same arguments forever.For example:
CREATE FUNCTION add_numbers(a INTEGER, b INTEGER) RETURNS INTEGER AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql IMMUTABLE;
Security Definer: By default, functions run with the permissions of the user that calls them. However, if you specify the function as SECURITY DEFINER
, it will run with the permissions of the user who created the function.
Cost and Rows: You can provide hints to the optimizer about the execution cost of the function using the COST
keyword and, for set-returning functions, the number of rows the function will return using the ROWS
keyword.
Remember, functions are powerful tools in PostgreSQL, allowing you to encapsulate logic, perform computations, and even modify the database. Always test your functions thoroughly to ensure they work as expected and have no unintended side effects.
Defining user-defined functions in PostgreSQL:
CREATE OR REPLACE FUNCTION your_function() RETURNS returnType AS $$ -- Function logic here $$ LANGUAGE plpgsql;
Creating stored procedures with CREATE FUNCTION in PostgreSQL:
CREATE OR REPLACE FUNCTION your_procedure() RETURNS VOID AS $$ -- Procedure logic here $$ LANGUAGE plpgsql;
Input and output parameters in CREATE FUNCTION in PostgreSQL:
CREATE OR REPLACE FUNCTION add_numbers(a INTEGER, b INTEGER) RETURNS INTEGER AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;
Returning multiple values from a function in PostgreSQL:
OUT
parameters for multiple return values.CREATE OR REPLACE FUNCTION get_user_info(user_id INTEGER) RETURNS TABLE (username VARCHAR, email VARCHAR) AS $$ -- Function logic here $$ LANGUAGE plpgsql;
Managing security and permissions for functions in PostgreSQL:
GRANT EXECUTE ON FUNCTION your_function() TO your_user;
Overloading functions in PostgreSQL:
CREATE OR REPLACE FUNCTION concatenate_strings(a TEXT, b TEXT) RETURNS TEXT AS $$ BEGIN RETURN a || b; END; $$ LANGUAGE plpgsql; CREATE OR REPLACE FUNCTION concatenate_strings(a TEXT, b TEXT, c TEXT) RETURNS TEXT AS $$ BEGIN RETURN a || b || c; END; $$ LANGUAGE plpgsql;
Dropping functions with DROP FUNCTION in PostgreSQL:
DROP FUNCTION your_function();
Function overloading and polymorphism in PostgreSQL:
CREATE OR REPLACE FUNCTION add_values(a INTEGER, b INTEGER) RETURNS INTEGER AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql; CREATE OR REPLACE FUNCTION add_values(a DOUBLE PRECISION, b DOUBLE PRECISION) RETURNS DOUBLE PRECISION AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;