SQL are two ways to solve the divide by zero error

In a real project, we may encounter sql statement seeking percentages, ratios, etc. with the division. At this time, we may encounter denominator is zero.

Here are two kinds of solutions:

 

1. NULLIF function.

First talk about the syntax NULLIF function:

NULLIF(expr1,expr2)

This means that: if expr1 <> expr2, then returns expr1; if expr1 = expr2 words, NULL is returned.

 

2. case when statement.

case when the denominator = 0 then NULL else numerator / denominator

 

Both of these methods are feasible, personally I think that, considering the compatibility of each database, have an advantage with the second method.

--  Nullif(expr1,expr2) expr1=expr2返回null;expr1<>expr2返回expr1
--  Case When 分母=0 Then null Else 分子/分母 End
--  Case 分母 When 0 Then null Else 分子/分母 End
--  MySQL
 
SET @var1=10, @var2=20, @var3=0;
  
SELECT
  @var1/NULLIF(@var2,0),
  @var1/NULLIF(@var3,0),
  CASE @var2 WHEN 0 THEN NULL ELSE @var1/@var2 END AS var1_var2,
  CASE @var3 WHEN 0 THEN NULL ELSE @var1/@var3 END AS var1_var3;

 

 

 

Published 363 original articles · won praise 74 · views 190 000 +

Guess you like

Origin blog.csdn.net/sinat_26811377/article/details/104664145