Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle View problem with Select and division by zero

I want to create an view in Oracle which calculates an "utilization rate in percent".

AS SELECT
  sw.SWITCH_ID,
  sw.ASSET_ID,
  sw.SYSTEMNAME,
  sw.MAX_INSTALLABLE_PORTS,
  sw.INSTALLED_PORTS,
  sw.USED_PORTS,
  (sw.INSTALLED_PORTS/sw.MAX_INSTALLABLE_PORTS)*100 AS UTIL_INSTALLED_PORTS,
  sw.RES_INFRASTRUCTURE_PORTS,
  sw.USED_INFRASTRUCTURE_PORTS,
  sw.FREE_INFRASTRUCTURE_PORTS,
  (sw.INSTALLED_PORTS/sw.MAX_INSTALLABLE_PORTS)*100 AS UTIL_INFRASTRUCTURE_PORTS,
  sw.RESERVED_DEVICE_PORTS,
  sw.USED_DEVICE_PORTS,
  sw.FREE_DEVICE_PORTS,
  (sw.FREE_DEVICE_PORTS/sw.RESERVED_DEVICE_PORTS)*100 AS UTIL_DEVICE_PORTS,
  sw.RUN_DATE

Problem: sometimes sw.INSTALLED_PORTS or sw.MAX_INSTALLABLE_PORTS can be NULL (same for other UTIL Rows).

Is there any nice way to do something like:

if (sw.INSTALLED_PORTS or sw.MAX_INSTALLABLE_PORTS == null) 
      UTIL_INSTALLABLE_PORTS = null 
else (sw.INSTALLED_PORTS/sw.MAX_INSTALLABLE_PORTS)*100 AS UTIL_INSTALLABLE_PORTS,
like image 301
opHASnoNAME Avatar asked Nov 21 '25 04:11

opHASnoNAME


2 Answers

or a little shorter:

sw.INSTALLED_PORTS/NULLIF(sw.MAX_INSTALLABLE_PORTS,0)

Regards, Rob.

like image 153
Rob van Wijk Avatar answered Nov 23 '25 20:11

Rob van Wijk


Divizion by NULL is not the same as divizion by zero (as you reference the problem in the title).

select 1/null from dual = null
select null/null from dual = null

So you'll automatically get what you want by (sw.INSTALLED_PORTS/sw.MAX_INSTALLABLE_PORTS)*100.

I think, the problem is when sw.MAX_INSTALLABLE_PORTS is zero. In this case you can use the following:

case
  when sw.MAX_INSTALLABLE_PORTS = 0 then null
  else (sw.INSTALLED_PORTS/sw.MAX_INSTALLABLE_PORTS)*100
end
like image 20
Egor Rogov Avatar answered Nov 23 '25 19:11

Egor Rogov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!