Postgres nested if requested

Could you tell me why the following does not work in postgres sql ?:

See updated code below 

UPDATE:

I expect the request to return "0.30" as a float. This design is for testing purposes only, I have some complex queries that depend on this conditional structure ... BUt I do not know how to fix it ..

Result:

 ERROR: syntax error at or near "1" LINE 4: if 1=1 then 

UPDATE:

This construct appears in the function ... so I want to do the following:

 CREATE FUNCTION f_test(myvalue integer) RETURNS float AS $$ BEGIN select ( case (select '1') when '1' then if 1=1 then 0.30::float else 0.50::float end else 1.00::float end ); END; $$ LANGUAGE plpgsql; select f_test(1) as test; 

Error message see above.

+7
sql postgresql if-statement case
source share
2 answers

There is no syntax IF expr THEN result ELSE result END for regular SQL queries in Postgres. Since there is no IF() function, as in MySQL, you should use CASE :

 select ( case (select '1') when '1' then case when 1=1 then 0.30::float else 0.50::float end else 1.00::float end ); 
+9
source share

I donโ€™t know what you are trying to achieve with this function, but here is the working version.

 CREATE FUNCTION f_test(myvalue integer) RETURNS float AS $$ BEGIN IF myvalue = 1 THEN IF 1=1 THEN RETURN 0.30::FLOAT; ELSE RETURN 0.50::FLOAT; END IF; ELSE RETURN 1.0::FLOAT; END IF; END; 

The function returns 0.3 if the input value is 1, otherwise it will return 1. Edit: Note that the function is never returned by the function.

+1
source share

All Articles