-2

I have a table tab1 with four columns col1, col2, col3 and col4.

I want to create a function like f4(a) where a is defined by user and if user types select f4(col1) he gets column tab1.col1.

Is there any way to create such function in PostgreSQL?

1
  • The question is to broad. You should try something and come back if you have a specific problem, not just a requirement dump. Hint: You can query pg_attribute and join pg_class and possibly pg_namespace. And you should think about how to handle the case, when more than one table has a column named like the function's input. Commented May 8, 2021 at 22:45

1 Answer 1

2

There is no apparent reason to complicate matters with a function. Simply:

SELECT col1 FROM tab1;

To achieve what you ask for, you need dynamic SQL because SQL does not allow to parameterize identifiers - or anything but values for that matter:

CREATE OR REPLACE FUNCTION f4(_col text)
  RETURNS TABLE (col_x text)
  LANGUAGE plpgsql AS
$func$
BEGIN
   RETURN QUERY EXECUTE 
   format('SELECT %I FROM tab1', _col);
END
$func$;

Call:

SELECT * FROM f4('col1');

Further reading:

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

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.