Best index for case insensitive match on one field and ordering by another field

All we need is an easy explanation of the problem, so here it is.

I want to run a query like this:

SELECT *
FROM "core_user"
WHERE UPPER("core_user"."email"::text) = UPPER('[email protected]')
ORDER BY "core_user"."last_login" DESC
LIMIT 1;

I’ve tried adding two indexes:

CREATE INDEX core_user_upper_idx ON public.core_user USING btree (upper((email)::text));
CREATE INDEX core_user_last_lo_0521b8_idx ON public.core_user USING btree (last_login);

core_user_upper_idx works well if I remove the ordering clause, but in its current state explain gives

 Limit  (cost=0.29..10.33 rows=1 width=431)
   ->  Index Scan Backward using core_user_last_lo_0521b8_idx on core_user  (cost=0.29..5531.53 rows=551 width=431)
         Filter: (upper((email)::text) = '[email protected]'::text)

which doesn’t perform very well.

Is there a better index for me to add here? I’m a bit unsure as to whether I should "prioritise" the email or last_login fields.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

A multicolumn expression index should serve your particular query best:

CREATE INDEX ON public.core_user (upper(email), last_login DESC);

If last_login can be NULL, consider NULLS LAST – in index and query.
The rule of thumb is: equality first, range later. See:

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply