Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql unique value or empty string

Tags:

sql

mysql

unique

I have an email mailing list table. There is an activation key for each user that signs up. The activation key is initially created upon signup. Each key is unique.

Once the user confirms registration this is an emptry string in the database.

Is there a way of me creating a unique contraint if there is null in the field.

In other words all value if not null or emptry string that are unique are allowed.

I set to unique and allow null but this does not work. I cant enter null and unique values, i.e. null multiple times when set to null unique

like image 464
Matthew Chambers Avatar asked May 27 '26 13:05

Matthew Chambers


2 Answers

No, you won't be able to create a unique constraint like that because a unique constraint is just that, unique, and multiple rows with NULL or an empty string would be duplicated rows. However, I would recommend you not empty out this column and rather use a boolean field that indicates registration was confirmed - it's a lot more straight forward and then you can use a unique constraint on that field.

like image 180
Mike Perrenoud Avatar answered May 30 '26 04:05

Mike Perrenoud


in mysql

column or unique index only check constraint when all values filled without null values

like image 29
ali saebifar Avatar answered May 30 '26 03:05

ali saebifar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!