My mistake. I have updated the query in the gist: cte1 should have been 
referenced in cte2. 

The query plans are correct. It was just the query in the gist that was 
incorrect (I was just verifying cte1 was the culprit – without it the query is 
fast too).

 

This SQL query is a result of translating a FHIR query into SQL. These queries 
are generated on the fly from user input. The chains will not always be linear. 
But I guess I could write an optimizer that rewrites linear parts as JOINS. If 
that would result in better query plans.

 

I have done a few simple experiments in the past comparing CTEs like this to 
JOINS, but the resultant query plans were the same. CTEs seemed easier to 
follow when troubleshooting issues, so I left them as such. Do JOINs become 
better than CTEs at a certain point?

 

I will attempt to rewrite the query with JOINs on Monday to see if it makes a 
difference. It might be tricky, the relationship from resource table to search 
parameter tables is often a 1 to many.

 

Reply via email to