Search code examples
sql-serverselectnulldivide-by-zero

How to avoid division by 0 in ms-sql select statement?


I've read about nullif, but haven't been able to put together a SELECT statement to use it properly:

Select (num/total) as percent ...

If total is 0, I want to return Null. How do I revise the statement?

if I say

select (num/nullif(total, 0)) as percent ...

what does it mean to divide by Null?


Solution

  • You could use CASE:

    SELECT [percent] = CASE WHEN total = 0 THEN NULL ELSE (num/total) END 
    FROM Table