Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql function with if statement

How can I make this pseudo code to work in Postgresql:

create or replace function getf(arg character varying(255)) returns int
as $$
if arg = 'a' then return 1;
else return 2;
$$ language sql;

Based on argument I need to return some values and there is no other table I need to query. Just need to build a logic inside function. Tried to replace if with when clause, but could not figure out how to do it.

Thanks!

like image 683
Edijs Petersons Avatar asked Sep 20 '25 02:09

Edijs Petersons


2 Answers

create or replace function getf(arg character varying(255)) returns int as $$
begin
  if arg = 'a' then
    return 1;
  else 
    return 2;
  end if;
end; $$ language plpgsql;

Note that this is a PL/pgSQL function.

The online manual has an excellent chapter on PL/pgSQL. That should provide everything you need to get started writing procedural function with ample support for logical branching.

like image 103
Patrick Avatar answered Sep 22 '25 19:09

Patrick


Using sql language, you can do it using case when:

create or replace function getf(arg character varying(255)) returns int as
 $$

select case 
        when arg = 'a' 
         then 1
         else 2 
       end

$$ language sql;
like image 25
Houari Avatar answered Sep 22 '25 19:09

Houari