IF-THEN-ELSE statements in postgresql

user2311028

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

Joseph Victor Zammit

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related