views:

183

answers:

2

Looking for a data type that is similar to VARCHAR as to the values I would like, but is there a way to have a MIN/MAX character length?

VARCHAR(6,10)

This would have a minimum of 6 characters and a maximum of 10 characters.

+1  A: 

This is called CHECK constraint in SQL and it is ignored by MySQL.

The CHECK clause is parsed but ignored by all storage engines.

newtover
So something like this: CHECK (LENGTH(fieldName) >= 6 AND LENGTH(fieldName) <= 10)
Phill Pafford
@Phill Pafford: yes
newtover
@Phill Pafford: do you not need this for MySQL?
Cez
@cez yes MySQL.
Phill Pafford
@Phil This answer doesn't work in MySQL though, so your constraints aren't enforced in the database
Cez
crap and thnx, you're right
Phill Pafford
+2  A: 

You could add a trigger to throw an exception when the values are outside of the range, e.g.

DELIMITER $$

CREATE TRIGGER `insert_table_var` BEFORE INSERT ON `table` 
FOR EACH ROW
BEGIN
     DECLARE str_len INT DEFAULT 0;
     DECLARE max_len INT DEFAULT 10;
     DECLARE min_len INT DEFAULT 6;

     SET str_len = LENGTH(NEW.col);

     IF str_len > max_len OR str_len < min_len 
     THEN
           CALL col_length_outside_range_error();
     END IF;
END $$
DELIMITER ;;

Whilst SIGNAL is not available, calling an undefined stored procedure would suffice (in this case col_length_outside_range_error). Otherwise, I think that the application using the database is going to need to do the checks.

Cez