IF-THEN-ELSE statements in postgresql

SqlPostgresql

Sql Problem Overview


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

Sql Solutions


Solution 1 - Sql

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

Solution 2 - Sql

case when field1>0 then field2/field1 else 0 end as field3

Solution 3 - Sql

In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). For example,

select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from (     (select 'abc' as x, '' as y)
 union all (select 'def' as x, 'ghi' as y)
 union all (select '' as x, 'jkl' as y)
 union all (select null as x, 'mno' as y)
 union all (select 'pqr' as x, null as y)
) q

gives:

 coalesce | coalesce |  x  |  y  
----------+----------+-----+-----
 abc      | abc      | abc | 
 ghi      | def      | def | ghi
 jkl      | jkl      |     | jkl
 mno      | mno      |     | mno
 pqr      | pqr      | pqr | 
(5 rows)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2311028View Question on Stackoverflow
Solution 1 - SqlJoseph Victor ZammitView Answer on Stackoverflow
Solution 2 - SqlThanos DarkadakisView Answer on Stackoverflow
Solution 3 - Sql18446744073709551615View Answer on Stackoverflow