简体   繁体   中英

Allow only positive numbers in MariaDB column

I need to ensure that the numbers inserted into a column are positive (ie greater than zero), but could not find a way to do it. Neither decimal type's documentation nor Numeric type overview provide a solution (or a trick) that would allow me to set such a constraint on the database column.

I know there is the unsigned modifier, but it only says that the value may not be negative (ie less than zero) and leaves zero as a valid value for unsigned columns.

Is there a way to enforce this on the database schema level? If not, I can trivially enforce the rule in the code, but I'd like to keep type information explicit in the schema.

MariaDB 10.2 supports CHECK constraints .

MariaDB [test]> CREATE TABLE t1 (i INT CHECK(i>0));
Query OK, 0 rows affected (1.04 sec)

MariaDB [test]> INSERT INTO t1 VALUES (1);
Query OK, 1 row affected (0.08 sec)

MariaDB [test]> INSERT INTO t1 VALUES (0);
ERROR 4025 (23000): CONSTRAINT `i` failed for `test`.`t1`
MariaDB [test]> INSERT INTO t1 VALUES (-1);
ERROR 4025 (23000): CONSTRAINT `i` failed for `test`.`t1`
MariaDB [test]> 
MariaDB [test]> SELECT @@version;
+----------------+
| @@version      |
+----------------+
| 10.2.6-MariaDB |
+----------------+
1 row in set (0.00 sec)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM