1

I am trying to create a function that will execute different SQL based on provided input to the function (i.e. IF ELSE). I am trying something like below but keep getting a syntax error. Does anyone know what I am doing wrong? Any pointers will be greatly appreciated!

CREATE or replace FUNCTION sales_price(group_by text) 
RETURNS table(first_name text, price decimal)
AS $$

  IF group_by="x" THEN
    select first_name, price from table1;
  ELSIF group_by="y" THEN
    select first_name, price from table2;
  END IF;
$$ LANGUAGE SQL IMMUTABLE;

1 Answer 1

3

You have several issues, but the biggest is sql rather than plpgsql:

CREATE or replace FUNCTION sales_price(group_by text) 
RETURNS table(first_name text, price decimal)
AS $$
BEGIN
  IF group_by = 'x' THEN
    return query select t1.first_name, t1.price from table1 t1;
  ELSIF group_by = 'y' THEN
    return query select t2.first_name, t2.price from table2 t2;
  END IF;
END;
$$ LANGUAGE plpgsql;

Here is a db<>fiddle.

I removed the IMMUTABLE because the function is not (well, I suppose you might know that the underlying tables never change).

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

3 Comments

Thank you for this! Super helpful to see where my mistakes were.
How do you do nested ifs in the return query? For example if I have another variable "joined_to" and based on that I want to union a table. Can I do something like IF group_by = 'x' THEN return query select t1.first_name, t1.price from table1 t1 IF joined_to="a" THEN UNION ALL SELECT * from table3; END IF;
@zeroanthem86: This function isn't IMMUTABLE, it does a table lookup. postgresql.org/docs/current/sql-createfunction.html

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.