Avoid Dividing by Zero in MySQL

Last updated 2 years ago

...

You’d like to avoid the “division by zero” error.

For this example , I am using two table one is subjects and second one is marks.

subjects

idsubject_namesubject_marks
1Math100
2English100

 

marks

marks_idmarks_student_idmarks_subject_idmarks_obtain
12140
2120

 

We shall perform a division operation of "subject_marks" by "marks_obtain" and display a table containing an additional column named "divided," that shall hold the outcome of the division process.

 

Method 1.

SELECT *, subjects.subject_marks / NULLIF(marks_obtain, 0) AS divided FROM marks LEFT JOIN subjects ON subjects.id=marks_subject_id;

Output:

marks_idmarks_student_idmarks_subject_idmarks_obtainidsubject_namesubject_marksdivided
121401Math1002.5
21202English100NULL

 

Method 2.

SELECT *, CASE WHEN marks_obtain = 0 THEN NULL ELSE subjects.subject_marks / marks_obtain END AS divided FROM marks LEFT JOIN subjects ON subjects.id=marks.marks_subject_id;

Output:

marks_idmarks_student_idmarks_subject_idmarks_obtainidsubject_namesubject_marksdivided
121401Math1002.5
21202English100NULL


The initial method 1 involves utilizing the NULLIF() function, which requires two numerical inputs. In cases where the initial input matches the second input, the function outputs NULL. When marks_obtain equals zero, the divisor becomes NULL; hence, the outcome of the division operation would be NULL.

The alternative approach involves utilizing the CASE statement. Whenever the condition succeeding the WHEN keyword is satisfied (in this particular scenario, the condition implies that marks_obtain is equal to zero), we indicate that the output should be NULL. Conversely, if the condition is not satisfied, the division is carried out normally.


Top SQL Queries for Data...

Mastering advanced SQL techniques can greatly enhance your data analysis capabilities, allowing you...

Read It

An Introduction To CSS Pr...

CSS or Cascading Style Sheets have become a really popular programming language in recent times and...

Read It



----Advertisement----