Warm tip: This article is reproduced from stackoverflow.com, please click
mysql nullable sql check-constraints

Check Constraint for Nullable Phone Numbers Column

发布于 2020-03-30 21:13:55

Constraint to check on MySQL server-side if a phone number consists of only numbers or not and whether it has ten digits or not.

I have the following create table query where mobile is the name of the field, storing the phone numbers of people: -

CREATE TABLE `users` (
  --Other columns

  `mobile` int UNSIGNED DEFAULT NULL, 

) ENGINE=InnoDB;

As indicated, the mobile column can be NULL. Hence, I can't apply direct length check constraints and other regex constraints. What would be a feasible check constraint, if any?

P.S. - I have assumed the phone numbers to be an INTEGER. I have read suggestions for making it varchar.

EDIT - (Take care of the version)

Prior to version 8.0, MySQL didn't enforce the check constraints. It allowed them to be written in CREATE TABLE statements, parsed them and ignored them.

Here's some useful documentation from MySQL Reference Manual:

Prior to MySQL 8.0.16, CREATE TABLE permits only the following limited version of table CHECK constraint syntax, which is parsed and ignored:

CHECK (expr)

Questioner
Akash Das
Viewed
17
GMB 2020-01-31 18:11

It has been vastly commented already that a phone number should be stored as string instead of an integer (a typical example being phone numbers that start with 0).

You could use the following check constraint:

check(mobile is null or mobile regexp '^[0-9]{10}$')

This ensures that mobile is either null or contains exactly 10 digits.

If you want to ensure that the phone number contains only digits but not necessarily 10 digits, then you can change the quantifier from 10 to +:

check(mobile is null or mobile regexp '^[0-9]+$')