Search code examples
sqlnulldivide

Divide Null by a number in SQL


I got a question: if I have a Product table in SQL which has columns Product ID, TotalPrice, NumberOfUnits

Now I need to calculate the unitPrice of the product.

This can be calculated by dividing the TotalPrice by NumberOfUnits.

Now the question is: if the totalPrice is Null and NumberOfUnits is 45.

What will the output be?

Select 
    ProductID,
    (TotalPrice / NumberOfUnits) as UnitPrice 
from ProductTable

What will be the output?

And if the answer is null, how can we handle this?


Solution

  • Null = NULL.

    SELECT NULL / 45
    

    Result

    Column1
    NULL
    

    Handling would be...

    SELECT IsNull(NULL, 0) / 45
    

    Result

    Column1
    0