Search code examples
mysqldatemaxmincreate-table

How to set mysql date minimum and maximum value?


Is it possible to set minimum and maximum values in MySQL table definition?

For example:

CREATE TABLE `tbl` (
    `id` BIGINT UNSIGNED NOT NULL PRIMARY KEY,
    `born` DATE MIN('1900-01-01') MAX('1999-12-31')
);

Solution

  • If I understand you correctly you can use triggers to enforce date range:

    CREATE TABLE `tbl` (
        `id` BIGINT UNSIGNED NOT NULL PRIMARY KEY,
        `born` DATE
    );                 
    
    CREATE TRIGGER `tbl_trg_ins` BEFORE INSERT ON  `tbl`
    FOR EACH ROW
    BEGIN
        IF (NEW.`born` < '1900-01-01' OR NEW.`born` > '1999-12-31') THEN
        SIGNAL SQLSTATE '10000'
            SET MESSAGE_TEXT = 'check constraint on tbb failed during insert';
        END IF;
    END;
    
    CREATE TRIGGER `tbl_trg_upd` BEFORE UPDATE ON  `tbl`
    FOR EACH ROW
    BEGIN
        IF (NEW.`born` < '1900-01-01' OR NEW.`born` > '1999-12-31') THEN
        SIGNAL SQLSTATE '10000'
            SET MESSAGE_TEXT = 'check constraint on tbl failed during update';
        END IF;
    END;
    
    INSERT INTO `tbl`
    VALUES (1, '1990-12-12');
    
    -- INSERT INTO `tbl`
    -- VALUES (2, '2001-12-12');
    -- 'check constraint on tbb failed during insert'
    

    SqlFiddleDemo

    When user tries to update/insert value that is not between 1900-01-01 and 1999-12-31, he will get error.