There's no declarative way to restrict the values stored in a column to the domain that was specified: "five digit numbers".
We take that to mean that this will be stored as a numeric, and there won't be decimal point. That is, the specification is to allow only positive five digit integers, in the range 10000
to 99999
.
To have the database enforce this type restriction, we would need to implement BEFORE INSERT and BEFORE UPDATE triggers.
As an example, we could raise a generic SQLSTATE as an error, whenever an attempt to insert or update a value that is out of range.
Assuming mycol
is defined as integer type:
DELIMITER $$
CREATE TRIGGER mytable_bi
BEFORE INSERT ON mytable
FOR EACH ROW
BEGIN
IF NOT ( NEW.mycol >= 10000 AND NEW.mycol <= 99999 ) THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'value out of range 10000 to 99999'
, COLUMN_NAME = 'mycol'
, TABLE_NAME = 'mytable'
;
END IF;
END$$
A similar BEFORE UPDATE
trigger would also be required.
In earlier versions of MySQL don't support SIGNAL
, we can emulate it by causing an error to be thrown. (Throwing an error will prevent the firing INSERT or UPDATE operation from completing successfully.) In place of SIGNAL
, we can execute a SQL statement that is guaranteed to throw an error.
Another alternative is to use a foreign key constraint against a "domain table".
Create a table with a single column (same datatype as mycol
) and populate it with the set of all possible valid values, and omit all invalid values.
CREATE TABLE five_digit_integers (i INT NOT NULL PRIMARY KEY );
INSERT INTO five_digit_integers VALUES (10000),(10001),(10002),...;
...
INSERT INTO five_digit_integers VALUES ...,(99998),(99999);
Then, create a foreign key constraint:
ALTER TABLE mytable
ADD CONSTRAINT FK_mytable_mycol_five_digit_integer
FOREIGN KEY (mycol) REFERENCES five_digit_integer (i)
;
Attempts to insert or update "out of range" values in mytable.mycol will result in a foreign key constraint error, and prevent the INSERT or UPDATE from completing successfully.
Of course, this doesn't prevent someone from inserting additional values into the five_digit_integers
table, or from getting around the constraint by issuing a SET FOREIGN_KEY_CHECKS=0
.