Postgres Custom Functions

Postgres custom functions allow you to customize your database schema by defining a set of operations that can include several statements such as declarations, assignments and conditional workflows. Postgres functions are similar to views but allow more procedural computations and can take arguments. Custom SQL functions are also referred to as stored procedures.

We can create the following function that we can call later to search articles based on the input text argument search.

CREATE FUNCTION search_articles(search text)
RETURNS SETOF article AS $$
    SELECT *
    FROM article
    WHERE
      title ilike ('%' || search || '%')
      OR content ilike ('%' || search || '%')
$$ LANGUAGE sql STABLE;

Postgres custom functions can be exposed in Hasura's GraphQL schema as a top-level field or as a computed field for a table. They are typically used for performing custom business logic in the database.

Refer to Custom SQL functions and Computed fields for more use cases and for instructions on how to create and expose Postgres custom functions in Hasura.

Last updated