2

I am trying to create a function which is as follows

create function public.getSomething(
        value1 integer
    )
      returns table (
             id integer,
             name varchar(20)
    
              ) as
    $$
    BEGIN
    
        IF value1 = 0 THEN
        
            select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where 
            a.column = something and b.column = something;
            
        END IF;
    
        IF value1 = 1 THEN
        
            select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where 
            a.column = something and b.column = something;
            
        END IF;
    
    END;
            
    $$ language SQL;

But when I am trying to Create, I am getting the following error

ERROR:  syntax error at or near "if" 

I tried changing the Language from SQL to plpgsql. But this time I am getting

Error: query has no destination for result data
Hint: if you want to discard the results of a select use perform instead

then I replaced the Select with Perform. This time the function is created but when I am calling it There is no result!!

What am I doing wrong? Is there any alternative? I am Using postgres version 12.3

2
  • 3
    if .. else can only be used in PL/pgSQL, not in SQL. In PL/pgSQL, you need return query select .. postgresql.org/docs/current/… Commented Dec 1, 2020 at 12:24
  • thanks @a_horse_with_no_name. It worked. Commented Dec 3, 2020 at 5:51

1 Answer 1

2

Your function with slight modifications (in capitals):

  1. Language is plpgsql;
  2. In a SQL function you simply return the result of a query. In a plpgsql function you have to use RETURN statement to return anything. As you do not want to discard the query results but return them, add RETURN QUERY before the SELECT statements.
create OR REPLACE function public.getSomething(value1 integer)
returns table (id integer, name varchar(20)) as
$$
    BEGIN

        IF value1 = 0 THEN
            RETURN QUERY select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where 
            a.column = something and b.column = something;
        END IF;

        IF value1 = 1 THEN
            RETURN QUERY select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where 
            a.column = something and b.column = something;
        END IF;

    END;
            
$$ language PLPGSQL;
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.