Video in progress

There is an index on the `email` column, but the query `WHERE lower(email) = lower(:email)` doesn't use it. Why, and how do you fix it?

The index is built on the values of email itself, and the result of lower(email) isn't in the index, so the planner can't use it. The fix is to create an expression index on exactly that expression, or to store the data already lowercased when you write it.

📖 Answer

CREATE INDEX idx_users_email_lower ON users (lower(email));

Now WHERE lower(email) = 'ali@mail.uz' goes to an Index Scan. The expression in the condition must be exactly the same as the one in the index: this index won't work for upper(email) or lower(trim(email)).

The same problem shows up in other forms:

WHERE date(created_at) = '2026-11-03'           -- the created_at index doesn't work
WHERE created_at >= '2026-11-03'
  AND created_at <  '2026-11-04'                -- works, no expression

WHERE amount + 0 > 100                          -- the expression "switches off" the index
WHERE phone = 998901234567                      -- if phone is text, the type conversion gets in the way too

Make it a rule: leave the indexed column "bare" in the condition, and apply the function to the value on the other side.

For email there's another option: the citext extension (a case-insensitive text type), or lowercasing with toLowerCase(Locale.ROOT) in the application before saving, with the unique constraint on that value too. Otherwise Ali@mail.uz and ali@mail.uz end up as two separate accounts.