How can we add a constraint which enforces a column to have only positive values.
Tried the following mysql statement but it doesn’t work
create table test ( test_column integer CONSTRAINT blah > 0);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You would use the keyword
unsignedto signify that the integer doesn’t allow a “sign” (i.e. – it can only be positive):You can read more about the numeric data types (signed & unsigned) here.
As far as an actual constraint to prevent the insertion-of negative values, MySQL has a
CHECKclause that can be used in theCREATE TABLEstatement, however, according to the documentation:For reference, here is how you would use it (and though it will execute absolutely fine, it just does nothing – as the manual states):
UPDATE (rejecting negative values completely)
I’ve noticed from a few of your comments that you want queries with negative values to be completely rejected and not set to
0(as a normal transaction into anunsignedcolumn would do). There is no constraint that can do this in-general (that I know of, at least), however, if you turn strict-mode on (withSTRICT_TRANS_TABLES) any query that inserts a negative value into an unsigned column will fail with an error (along with any-other data-insertion errors, such as an invalidenumvalue).You can test it by running the following command prior to your insert-commands:
And if it works for you, you can either update your MySQL config with
sql-mode="STRICT_TRANS_TABLES"or useSET @@GLOBAL.sql_mode = 'STRICT_TRANS_TABLES';(I’m not sure if theSETcommand will affect the global mysql config though, so it may be better to update the actual config-file).