Some Thoughts on Emails and Databases
For most of the web applications I've worked on treat email addresses as an attribute to the user. e.j.
CREATE TABLE users (
user_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
-- …
);
But a user can have more than one email. If for no other reason to still be able to access their account in the event their loose access to their email. Email addresses also have attributes we want to keep track of. E.j. whether we have verified the user the user controls the email address. To represent a 1-m relationship between a user and email addreses, for my blog I'm moving email addresses to a separate table:
CREATE TABLE blog.users (
user_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
username TEXT NOT NULL UNIQUE
);
create table blog.user_emails (
user_id integer not null,
email text not null,
primary key (user_id, email),
foreign key (user_id) references blog.users (user_id)
);
create unique index email id ON blog.users(lower(email));
A digression on case
Contrary to popular belief and necessary practical considerations, email has case-sensitive parts (h/t fanf). The local part is de iure case-sensitive, but de facto case-insensitive. The domain name is sometimes case-sensitive and sometimes case-insensitive. However in practice, in most of the email server the local part is case-insensitive.
People often use CamelCase when the local part is their name, e.j. JaneDoe@…. They don't use the same case consistently, different people use different casing for the same email address, etc. So in practice it is easier to treat email addresses as case-insensitive.
Pending Questions
For my current use-case the above is enough. In the case of a site that is open for registrations a verified attribute would be needed.. It could be a boolean or a nullable date if we want to record the time it was verified.
We also want to mark a single email as the primary email. My initial idea for how to achieve this would be a boolean attribute. However there is no way to enforce that there is only one true value per user as a check constraint, so I'm not satisfied with this approach.
An alternative design would be to use a priority column. The benefit of which would be to always have a primary email chosen as long as there is one email. Or given that we only care about choosing one row, we could use a timestamp that we can 'touch' to make the row the primary.
In both cases, if for convenience we need to treat the primary email as an attribute of the users table we could always add it as a generated column.