Set value 0 when the number is negative

Asked

Viewed 1,617 times

4

How do I assign 0 when the value in the column in Mysql is negative? Or is there some kind of data that only has positive numbers?

3 answers

11


Set your column to unsigned (no sign) this ensures that only positive values zero and null are valid entries.

In this example the first Insert already returns the error:

Data truncation: Out of range value for column 'n' at Row 1

Or if you check errors for warnings -1 will become 0.

create table t(
  id int(11) auto_increment primary key,
  n int(11) unsigned
);

insert into t (n) values(-1);
insert into t (n) values(2);
insert into t (n) values(0);
insert into t (n) values(null);

Example - sqlfiddle

4

Complementing the other answers, if you cannot change the structure of your table to use the unsigned as mentioned in the other answers, an alternative is to use the function GREATEST.

Example (sqlfiddle):

SELECT GREATEST(id, 0) from teste;

The function will show the highest value between id and 0, that is, if the value of id is negative, will show zero.

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.