I'm looking to write a postgresql query to do the following :
if(field1 > 0, field2 / field1 , 0)
I've tried this query, but it's not working
if (field1 > 0) then return field2 / field1 as field3 else return 0 as field3
thank youu
In Postgresql, we can use if-else in the select statement but in the place of IF, here we will use the CASE and WHEN that is similar to the if-else statement. Because, in a SELECT statement, we cannot use the IF directly.
The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command. You need a semicolon ( ; ) at the end of each statement in plpgsql (except for the final END ). You need END IF; at the end of the IF statement.
PL/pgSQL provides you with three forms of the if statements.
In PostgreSQL, the dollar-quoted string constants ($$) is used in user-defined functions and stored procedures. In PostgreSQL, you use single quotes for a string constant like this: select 'String constant'; When a string constant contains a single quote ('), you need to escape it by doubling up the single quote.
As stated in PostgreSQL docs here:
The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages.
Code snippet specifically answering your question:
SELECT field1, field2, CASE WHEN field1>0 THEN field2/field1 ELSE 0 END AS field3 FROM test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With