1

I have a table

CREATE TABLE table_name
(
    EmpId VARCHAR(50),
    Name VARCHAR(100)
)

How can I restrict the EmpId column to consist of two letters followed by 3-5 digits? The following are all examples of valid values:

ac236, ak2356, av23695, ak365

I tried using the following check constraint:

ALTER TABLE table_name
ADD CONSTRAINT ck_table_name CHECK (EmpId NOT LIKE'%[^a-zA-Z0-9 ]%')

However, it allows all combinations of letters & digits, such as "23" and "fads":

INSERT INTO table_name
  VALUES
('23', 'Test 2'),
('fabs', 'Test 2');

inserted rows with invalid EmpIDs

If a value violates the format, I'd like the query to fail and print error message. For example, if 'na23' were inserted as the EmpID, MySQL could say:

Empid should be ab123/ab1234/a12345 format

Initially, I was using MySQL 5.7.11-0ubuntu6-log (which, it turns out, doesn't support CHECK constraints), but have upgraded to MySQL 8.0.17.

3
  • What version of mysql are you on? Commented Jul 25, 2019 at 7:47
  • 5.7.11-0ubuntu6-log Commented Jul 25, 2019 at 8:37
  • 'Prior to MySQL 8.0.16, CREATE TABLE permits only the following limited version of table CHECK constraint syntax, which is parsed and ignored:' - dev.mysql.com/doc/refman/8.0/en/… . Either do this check in your front end or in a trigger. Commented Jul 25, 2019 at 10:09

1 Answer 1

1

Assuming it's MySQL >=8.0.16

check(EmpId regexp '^[a-z]{2}[0-9]{3,5}$')

Sign up to request clarification or add additional context in comments.

4 Comments

numeric values are also inserting
since you are using version less than 8.0.16 it won't work
,i have upgraded to 8.0.17 its working, how to add error message for this please let me know like Empid should be ab123/ab1234/a12345 format
It's quite a bit long, you need to use stored procedure to capture the error. There might be other solution too but you can't just do using only query. So where you need to show those error? If its in app side you can do it there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.