Michael
Michael

Reputation: 335

Return bool function with an aliased column name in PostgresQL

I have this pgsql function that checks if a person exists based on given personid. This function returns bool accordingly. From my query, I get the following:

enter image description here

However, I want the resulting column to have an alias so it's more readable among our developers. So instead of getting func_util__check_basicinfo, I want it to be person_exists.

Also the reason why the function is named this way is for our convention purpose.

Here's my query for this function:

CREATE OR REPLACE FUNCTION profile.func_util__check_basicinfo(person_id integer)
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
    begin
        return exists (
            select 1
            from profile.person_basicinfo pb
            where pb.personid = person_id
        );
    END;
$function$
;

Upvotes: 0

Views: 246

Answers (1)

user330315
user330315

Reputation:

A function's definition doesn't and can't define an alias. You will need to use the alias in the query where you use the function:

select func_util_check_basicinfo(...) as person_exists
from ...

By default a column will be named after the source in the query. So the column name always defaults to the function's name (this is true for all functions in Postgres). If you don't want to specify the column alias manually in every query, your only option is to rename the function to person_exists() (which I would find a much better name than the existing one to begin with)

Upvotes: 2

Related Questions