I want to run a query like this:
SELECT *
FROM "core_user"
WHERE UPPER("core_user"."email"::text) = UPPER('emailsearch@example.com')
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@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 "prioritise" the email or last_login fields.
DESCis not necessary. – Laurenz Albe Apr 29 '21 at 16:09last_logincan be NULL and the OP meantDESC NULLS LASTto begin with, it's faster that way. – Erwin Brandstetter Apr 30 '21 at 13:12