One of methods to handle zero-division error is to use case when structure.
set start '2024-05-20'
set end '2024-05-31'
set change (q2.close-q1.close)/q1.close
select q1.ticker,q1.date,
case when
q1.close=0 then null
else
:change end
from quote q1,quote q2
where
q1.ticker=q2.ticker
and q1.date= :'start'
and q2.date= :'end';
To use case when structure ,zero-division error avoided.
Now i want to get all the result whose change value is greater than 0.3.
select q1.ticker,q1.date,
case when
q1.close=0 then null
else
:change end
from quote q1,quote q2
where
q1.ticker=q2.ticker
and q1.date= :'start'
and q2.date= :'end'
and :change > 0.3;
It got the error info:
ERROR: division by zero
CONTEXT: parallel worker
How can write the postgresql select statement then?
2
Answers
You can’t define an operation in a variable
set change (q2.close-q1.close)/q1.close
and then expect that it will be somehow replaced on the query. You just do the operation on the query itself and for the> 0.3
you also use the case statement on the where clause (there are other ways of course).Also you should use the standard
join
operation, the one you are using is way outdatedYour first example attempts to only evaluate the division in your
select
list when it’s safe.Your second example does the same thing in the
select
list but then it tries to run the division for all rows in yourwhere
section, without that safety logic. It evaluates to this:You could correct it more than one way: demo at db<>fiddle
case
statement in yourwhere
section, the same way you did in yourselect
section. Rows that go down thenull
case branch will be discarded bywhere
:nullif()
The
quote
table is joined with itself so you canjoin...using(ticker)
thanks to the matching column name.