I have a model with two tables and an identifier which we are sorting by:
Explain analyze
SELECT          "item"."id"
FROM            "item"
INNER JOIN      "spec"
ON              (
                                "item"."spec_id" = "spec"."id")
WHERE "spec"."project_id" = '70d49665-b041-4afc-8d97-fde42904892f'
ORDER BY       "item"."identifier" DESC
LIMIT 50;
The field identifier is indexed, and "item"."spec_id" as well, but planner is yet scanning multiple rows (much more than exists in the same project):
 Limit  (cost=0.83..101.93 rows=50 width=20) (actual time=53.365..53.885 rows=50     loops=1)
   ->  Nested Loop  (cost=0.83..100806.47 rows=49854 width=20) (actual time=53.364..53.861 rows=50 loops=1)
         ->  Index Scan Backward using item_identifier on item  (cost=0.42..42273.79 rows=109215 width=36) (actual time=0.013..17.292 rows=19332 loops=1)
         ->  Index Scan using spec_pkey on spec  (cost=0.41..0.53 rows=1 width=16) (actual time=0.002..0.002 rows=0 loops=19332)
               Index Cond: (id = item.spec_id)
               Filter: (container_id = '70d49665-b041-4afc-8d97-fde42904892f'::uuid)
               Rows Removed by Filter: 1
 Planning time: 0.442 ms
 Execution time: 53.932 ms
(9 rows)
I guess that the optimiser need to sort the identifier first and only then run the filters, but why doesn't it run the filters and only then the do the sorting?
== edit == When I remove the order by stmt the
Index Scan Backward using item_identifier on item  (cost=0.42..42273.79 rows=109215 width=36) (actual time=0.013..17.292 rows=19332 loops=1)
is removed as well from plan
sortstep in your plan)