0

This is my column enter image description here

As It's length is specified (smallint(4)), but it does not constrain the range of values , so how can I constrain that only 4 digit values can be entered in this column

M.A.O.2
  • 37
  • 9

2 Answers2

1

"In query" validation can be done like this:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table (year INT NOT NULL);

INSERT INTO my_table SELECT 2016 FROM (SELECT 1) n WHERE 2016 BETWEEN 0 AND 9999;
Query OK, 1 row affected (0.00 sec)

SELECT * FROM my_table;
+------+
| year |
+------+
| 2016 |
+------+

INSERT INTO my_table SELECT 20161 FROM (SELECT 1) n WHERE 20161 BETWEEN 0 AND 9999;
Query OK, 0 rows affected (0.00 sec)

SELECT * FROM my_table;
+------+
| year |
+------+
| 2016 |
+------+
Strawberry
  • 33,750
  • 13
  • 40
  • 57
0

From MySQL manual:

MySQL supports an extension for optionally specifying the display width of integer data types in parentheses following the base keyword for the type. For example, INT(4) specifies an INT with a display width of four digits.

The display width does not constrain the range of values that can be stored in the column. Nor does it prevent values wider than the column display width from being displayed correctly. For example, a column specified as SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and values outside the range permitted by three digits are displayed in full using more than three digits.

So, you cannot limit only 4 digit values in mysql this way. And MySQL does not supports custom CHECK constraints. But you can create trigger like this and check value inside. Note, that SIGNAL works since MySQL 5.5.

Community
  • 1
  • 1
Andrew
  • 1,858
  • 13
  • 15