Best index for case insensitive match on one field and ordering by another field I want to run a query like this:
SELECT *
FROM &quot;core_user&quot;
WHERE UPPER(&quot;core_user&quot;.&quot;email&quot;::text) = UPPER('emailsearch@example.com')
ORDER BY &quot;core_user&quot;.&quot;last_login&quot; 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)
   -&gt;  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@EXAMPLE.COM'::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 &quot;prioritise&quot; the email or last_login fields.
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:

Multicolumn index and performance
Get the last 5 distinct values for each ID