Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make empty string as null value to allow duplicate empty strings in optional field?

I have an email field that's optional. The regex works fine accepting the empty string (^$) but now the issue is that the empty string is considered a unique entry. It will only allow one user to register without entering an email address. I know I have to set it to null, but not sure how.

Something like this:

Duplicate entry '' for key 'users_email_unique' empty field

Error: Duplicate entry '' for key 'email'

like image 312
Yuck Fou Avatar asked Dec 23 '22 09:12

Yuck Fou


2 Answers

You could use partial index:

CREATE UNIQUE INDEX idx_unq_tab_email ON tab(email) WHERE TRIM(email) <> '';

DBFiddle Demo

That way you still have UNIQUE constraint plus original value.

like image 113
Lukasz Szozda Avatar answered Jan 11 '23 22:01

Lukasz Szozda


Create a trigger that converts blanks to nulls on insert or update:

create trigger null_email
before insert or update on users
for each row
new.email = nullif(old.email, '')

Or convert blanks to nulls on insert:

insert into users (..., email, ...)
values (..., nullif(?, ''), ...)

The trigger is the better way, because it handles data from any source, whereas method 2 would require the insert/update SQL of every application to conform to the "no blanks" rule.

like image 26
Bohemian Avatar answered Jan 11 '23 23:01

Bohemian