lovespring
lovespring

Reputation: 19589

In MySQL, how to keep a column value not less then 0?

for some reason, I want the logic resident in MySQL, not in PHP.

Upvotes: 0

Views: 357

Answers (2)

Thorsten
Thorsten

Reputation: 13181

The Standard SQL answer would be a "Check Constraint" so you could declare certain checks for the column (also allowing other values than 0 and some functions), e.g.

create table a (
 col_a int CHECK col_a > 10 and col_a MOD 10 = 1);

However, these constraints are not explicitly checked in mySQL. (There are some constraints in newer versions of mySQL that can be checked, but that's a a different story).

The only way that seems to reliably work in mySQL is to write insert and update triggers that check the constraint and raise an error if the constraint is not satisfied.

Upvotes: 1

outis
outis

Reputation: 77450

Declare the column with the UNSIGNED attribute.

Upvotes: 4

Related Questions