← Back to SQL, page 11

sql-0215 · Medium mid

How do you make a case-insensitive email lookup use an index?

Create an index on the expression itself, CREATE INDEX ... ON users(lower(email)), and query with exactly the same expression, WHERE lower(email) = lower(?). SQLite and PostgreSQL both support expression indexes. Alternatives are storing emails already lowercased or, in SQLite, declaring the column COLLATE NOCASE.

Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
CREATE INDEX users_email_lower ON users(lower(email));
EXPLAIN QUERY PLAN SELECT id FROM users WHERE lower(email) = lower('Ana@X.com');
text
QUERY PLAN
SEARCH users USING INDEX users_email_lower (<expr>=?)

The plan uses the expression index because the WHERE clause matches the indexed expression exactly. A slightly different expression, such as upper(email), would not match.

Making it unique also prevents 'Ana@x.com' and 'ana@x.com' from both being registered:

sql
CREATE TABLE u2 (id INTEGER PRIMARY KEY, email TEXT);
CREATE UNIQUE INDEX u2_email ON u2(lower(email));
INSERT INTO u2 (email) VALUES ('Ana@x.com');
INSERT INTO u2 (email) VALUES ('ana@x.com');
-- error on purpose
text
Error: UNIQUE constraint failed: index 'u2_email'

PostgreSQL supports the same index form, and the citext extension offers a case-insensitive text type (not run here).

Whichever option you choose, apply it everywhere emails are compared: sign-up, login, password reset and admin search. A lookup path that skips the lowercasing will miss existing accounts or allow duplicates through another door.

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
CREATE INDEX users_email_lower ON users(lower(email));
EXPLAIN QUERY PLAN SELECT id FROM users WHERE lower(email) = lower('Ana@X.com');

-- error on purpose
CREATE TABLE u2 (id INTEGER PRIMARY KEY, email TEXT);
CREATE UNIQUE INDEX u2_email ON u2(lower(email));
INSERT INTO u2 (email) VALUES ('Ana@x.com');
INSERT INTO u2 (email) VALUES ('ana@x.com');

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Index the expression the query uses
  • The WHERE expression must match the index expression
  • A unique expression index enforces case-insensitive uniqueness
  • Storing normalized values is an alternative

Common mistakes

  • Indexing email and querying lower(email)
  • Normalizing case in the app for inserts but not for lookups

Follow-ups

  • How would COLLATE NOCASE on the column compare?
  • Can a generated column replace the expression index?

Tips

  • Mention the uniqueness benefit