As of Mysql 8.0.16, check constraints can be enforced:
CREATE TABLE socials (ssn varchar(9) NOT NULL,
UNIQUE KEY ssn (ssn),
CONSTRAINT socials_chk_1 CHECK ((length(ssn) = 9));
When you attempt to insert data of incorrect length, it fails:
insert into socials values('12345678'); -- too short
(3819, "Check constraint 'socials_chk_1' is violated.")
When you attempt to insert data of the correct length, it succeeds:
insert into socials values('123456789'); -- just right
Query OK, 1 row affected
But notice how the constraint has unexpected behavior when the varchar length matches the constraint length, and the input value is longer than expected:
insert into socials values('1234567800000'); -- too long
Query OK, 1 row affected
select * from socials;
+-----------+
| ssn |
|-----------|
| 123456789 |
| 123456780 |
+-----------+
What happened? It looks like MySQL is truncating the input string to the varchar length and then checking the constraint, which results in "123456780" being inserted, which is not the desired behavior. As a workaround, make the varchar field at least one character longer than the constraint length, and the check will validate as expected:
alter table socials change ssn ssn varchar(10);
and then try inserting data longer than the check length:
insert into socials values('1234567800000'); -- too long
(3819, "Check constraint 'socials_chk_1' is violated.")