Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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
–
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,
WHEN field1>0 THEN field2/field1
ELSE 0
AS field3
FROM test
–
–
–
–
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)
gives:
coalesce | coalesce | x | y
----------+----------+-----+-----
abc | abc | abc |
ghi | def | def | ghi
jkl | jkl | | jkl
mno | mno | | mno
pqr | pqr | pqr |
(5 rows)
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.