Search code examples
sqlpostgresqlif-statementpostgresql-12

IF ELSE in postgresql function


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


Solution

  • 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;