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'
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With