Set the value 0 when the number is negative

4

How can 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?

    
asked by anonymous 15.12.2017 / 18:53

3 answers

11

Set your column to unsigned (no sign) This ensures that only positive values of 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 it converts errors to 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

    
15.12.2017 / 19:01
4

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

Example (sqlfiddle):

SELECT GREATEST(id, 0) from teste;

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

    
15.12.2017 / 19:14
1

To not use any signs, use unsigned, question already answered in stackoverflow in English.

p>

To limit the value of the column you could use Check Constraint but MySQL does not support this type of constraint, hence you can create a thrigger to execute the desired behavior.

link

    
15.12.2017 / 19:05