3

In postgres I have a custom function that will join first and last name.

  CREATE FUNCTION full_name(u users) RETURNS varchar
  LANGUAGE plpgsql VOLATILE
  AS $$
    BEGIN
      RETURN CONCAT_WS(' ', u.first_name, u.last_name);
    END;
  $$;

It would be nice if I didn't have to set the the name of the column name and it was determined by the function eg.

eg. here I have to say the column name is full_name

SELECT
 full_name(users) as full_name

But it would be nice if it atomically name it full_name

SELECT
full_name(users)

Is this possible to set in a custom function?

3 Answers 3

2

As the function parameter is the name of the table, you don't have to pass it.

You can call it like this:

select users.full_name
from users;

Note that you have to prefix the function name with the table name. You can also use an alias, but you still need the prefix.

select u.full_name
from users u;

In that case the column from the result set will be named full_name (the name of the function)

Btw: you don't need PL/pgSQL for the function. A plain SQL will likely be faster for this. Eespecially when you declare it stable instead of volatile - the it can be inlined and the overhead of calling the function is eliminated.

Sign up to request clarification or add additional context in comments.

Comments

1

Try to use out parameter instead of returning the value:

CREATE FUNCTION full_name(in u users, out full_name varchar)
LANGUAGE plpgsql VOLATILE
AS $$
  BEGIN
    full_name := CONCAT_WS(' ', u.first_name, u.last_name);
  END;
$$;

and

SELECT * FROM full_name(users)

Comments

0

This could be a solution to your problem. Instead of passing users as parameter you can use the first_name and last_name as parameters to the function.

CREATE OR REPLACE FUNCTION full_name(character varying ,character varying)
 RETURNS character varying AS
$BODY$
declare
    l_nom ALIAS FOR $1;
    l_pnom ALIAS FOR $2;
begin

    RETURN CONCAT_WS(' ', l_nom, l_pnom);    
 end;$BODY$
 LANGUAGE plpgsql VOLATILE
COST 100;
     ALTER FUNCTION full_name(character varying ,character varying) OWNER TO postgres;

SELECT full_name(u.first_name, u.last_name) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.