If you pass this value in directly as part of the query string, how does it perform? It seems like calling the function to get this value may be creating a planning problem with the value unknown at plan time. If you were able to put the result on an analyzed temp table at least, I'd expect that the planner would have enough info to make good decisions.