On Feb 12, 2015 9:17 PM, "Tom Lane" <tgl@sss.pgh.pa.us> wrote:
> The planner might produce such a result if there's an opportunity
> to perform the sorting via an index on "alpha" (ie, the ORDER BY
> matches some index). If it has to do an explicit sort it's gonna
> do the join first.
>
> (If you have such an index, and it's not going for the plan you want,
> you might need to crank up the COST property of some_function to
> persuade the planner that it should try to minimize the number of calls
> even if that means a slower scan choice.)
>
> In both cases though, I rather wonder why you're using LATERAL at all, as
> opposed to just calling the function in the main query when you want its
> result. The query planner can't be expected to make up for arbitrary
> amounts of stupidity in the formulation of the submitted query.
Useful, many thanks. I'll try playing with cost changes and a more targeted index.
In my real code, the function actually returns a json hash from which several fields are extracted in the main select (why? Unpacking in the query saves some hassle in the app code...) So my plan was to use lateral to limit function calls to max once per row. Is there a better way, other than using a nested query?