PostgreSQL query division by zero error

I am trying to run the following query that calls me postgres error: division by zero

select 
    request_count,
    response_count, 
    (response_count*100) / (request_count+response_count) AS proportion 
from total_dummy_table; 

How to avoid and resolve the error division by zero?

Tried to fix using the following query, but getting the same result as above

SELECT 
    request_count,
    response_count,
    (response_count*100) / (request_count) AS proportion 
FROM 
    total_dummy_table
ORDER BY 
    (response_count*100) /(CASE request_count WHEN 0 Then NULL ELSE request_count END) DESC NULLS FIRST

Please let me know where I am doing wrong, or how I can fix it. Thank!

Waiting for result:

The request should return me something like below:

Request_count | Response_count | Proportion

1603423       |  585706        | 36.52

Quick note: The total_dummy_table table does not have a column name proportion, which is an addition to the result that calculated the proportion in it.

+4
source share
2 answers
select request_count,response_count, 
case 
    when 
    request_count+response_count = 0 then 0 
    else
(response_count*100) / (request_count+response_count) 
end AS proportion 
from total_dummy_table;
+6
source

NULLIF

something/NULLIF(column_name,0)

NULLIF(col,val)

CASE WHEN col=val THEN NULL ELSE col
+10

Source: https://habr.com/ru/post/1530301/


All Articles