Some notes 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. Like whether we have verified the user the user controls the email address.

So 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 issues

For my current use-case the above is enough. As I mentioned earlier for an open registration site we would need to add a verified attribute. It could be a boolean or a nullable date if we want to record the time it was verified.

We also want to be able to chose an active/primary email. There most straight forward way to do so would be another boolean attribute and a check to ensure that there is always one row for each user set to true. 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. The value could be cached in a stored column.