When creating reports I find myself frequently joining to ad-hock sub queries like this:
SELECT * FROM Customer c
JOIN (SELECT CustomerId,ContractId FROM Contract WHERE StartDate > GetDate()) co ON co.CustomerId = c.CustomerId
Obviously this is just a qucik demo sql, but it illustrates the point.
I am wondering if there are some performance concerns with these types of queries. Are there other good alternatives? Typically the sub queries are more complicated with aggregates etc..
I know in this case it would make more sense to just join to the contact table directly, but I am just trying to illustrate the general idea without having to provide a convoluted example.
Any feedback would be appreciated 🙂
Is this a common practice?
Not to be pedantic, but that’s not technically an ad-hoc query, which would be defined as a query created by the end-users of the system. Instead, your example is really just a sub-query.
To address your question, if you find yourself joining to the same sub-query more than once, you should create a view, and then join to that view instead. This would allow you to simplify your code, and make any future changes to the sub-query in a single location.
If you only use these sub-queries in a single report, and there’s nothing common between them across reports that could be placed in a view, then it’s really just another way of writing your query. There’s nothing necessarily bad about it, and it’s not uncommon, but you might consider alternate approaches, such as replacing your subquery with additional joins – this may offer you a better execution plan, but that will vary on several other factors, including which RBDMS this is for.