Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL 0 if negative value

So I want to turn negative value's into a 0. I found 2 solutions that do exactly the same:

SUM(IF(ordered_item.amount < 0, 0, ordered_item.amount)) as purchases

And

SUM(CASE WHEN ordered_item.amount < 0 THEN 0 ELSE ordered_item.amount END) as purchases

They give me both the same result, but which would give me the best performance? And is there maybe a simpler solution to turn negatives into 0.

like image 580
Bram Avatar asked Apr 30 '15 12:04

Bram


People also ask

How do I change negative values to zero in SQL?

select name, (case when (sum(case when TransTypeName like 'credit%' then amount else 0 end) - sum(case when TransTypeName like 'Debit%' then amount ) else 0 end)) *5/100)<0 then 0 else (sum(case when TransTypeName like 'credit%' then amount else 0 end) - sum(case when TransTypeName like 'Debit%' then amount ) else 0 ...

Can SQL store negative values?

So to answer your question, yes you can use the decimal datatype to store negative decimal numbers.

Can Int be negative SQL?

Introduction to MySQL INT typeAn integer can be zero, positive, and negative.


2 Answers

An alternate approach you could use is the GREATEST() function.

SUM(GREATEST(ordered_item.amount, 0)) as purchases 
like image 188
CodeNewbie Avatar answered Sep 23 '22 06:09

CodeNewbie


You can define the field as "unsigned" so no conversion would be required

CREATE TABLE ordered_item ( 
order_id INT UNSIGNED NOT NULL AUTO_INCREMENT, 
amount INT UNSIGNED NOT NULL, 
PRIMARY KEY (`order_id `) 
); 

https://dev.mysql.com/doc/refman/5.0/en/integer-types.html

like image 35
Volkan Ulukut Avatar answered Sep 24 '22 06:09

Volkan Ulukut