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

PostgreSQL - CREATE FUNCTION Statement

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:

Syntax:

CREATE FUNCTION function_name (parameter_name parameter_data_type,...)
RETURNS return_data_type
AS $$
-- function body
$$
LANGUAGE plpgsql;

Example:

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

Some points to consider:

  1. Parameters: Functions can have zero or more parameters. In the above example, the function add_numbers has two parameters of type INTEGER.

  2. 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.

  3. Function Body: The actual logic of the function is defined in the body. It's enclosed between the $$ delimiters.

  4. 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.

  5. 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;
  1. 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.

  2. 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.

  1. Defining user-defined functions in PostgreSQL:

    • Description: Creates a custom function with specified logic.
    • Code:
      CREATE OR REPLACE FUNCTION your_function()
      RETURNS returnType AS $$
      -- Function logic here
      $$
      LANGUAGE plpgsql;
      
  2. Creating stored procedures with CREATE FUNCTION in PostgreSQL:

    • Description: Functions in PostgreSQL are similar to stored procedures in other databases.
    • Code:
      CREATE OR REPLACE FUNCTION your_procedure()
      RETURNS VOID AS $$
      -- Procedure logic here
      $$
      LANGUAGE plpgsql;
      
  3. Input and output parameters in CREATE FUNCTION in PostgreSQL:

    • Description: Specifies input and output parameters for the function.
    • Code:
      CREATE OR REPLACE FUNCTION add_numbers(a INTEGER, b INTEGER)
      RETURNS INTEGER AS $$
      BEGIN
          RETURN a + b;
      END;
      $$
      LANGUAGE plpgsql;
      
  4. Returning multiple values from a function in PostgreSQL:

    • Description: Returns a composite type or uses OUT parameters for multiple return values.
    • Code:
      CREATE OR REPLACE FUNCTION get_user_info(user_id INTEGER)
      RETURNS TABLE (username VARCHAR, email VARCHAR) AS $$
      -- Function logic here
      $$
      LANGUAGE plpgsql;
      
  5. Managing security and permissions for functions in PostgreSQL:

    • Description: Grants appropriate permissions to users or roles for the function.
    • Code:
      GRANT EXECUTE ON FUNCTION your_function() TO your_user;
      
  6. Overloading functions in PostgreSQL:

    • Description: Creates multiple functions with the same name but different parameter lists.
    • Code:
      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;
      
  7. Dropping functions with DROP FUNCTION in PostgreSQL:

    • Description: Removes a function from the database.
    • Code:
      DROP FUNCTION your_function();
      
  8. Function overloading and polymorphism in PostgreSQL:

    • Description: Takes advantage of polymorphism to handle different data types.
    • Code:
      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;