patternsqlModerate
Check if any of the values is in a subquery result
Viewed 0 times
resulttheanysubqueryvaluescheck
Problem
I have a complicated subquery that returns a list of order IDs. I need to get a list of customers who have these orders. The problem is that there are two ways of assigning a customer to an order (one of two fields). I could just do stuff like this:
The problem is that the subquery is enormous, both in time it takes to execute, and in the screen space it takes. Is there a way to check if one of the fields contains one of the desired results?
select *
from Customers
where orderId in (select...)
or secondaryOrderId in (select ...)The problem is that the subquery is enormous, both in time it takes to execute, and in the screen space it takes. Is there a way to check if one of the fields contains one of the desired results?
Solution
Try:
Eg, if you were planning on:
Then you make it so that you only call your subquery once, and build your OR clause into it.
The whole point of this is to ensure that the complicated subquery is only executed one time. That doesn't happen with a CTE, or by replacing two INs with two EXISTSs.
where exists (select * ....
where Customers.orderId = ...
or Customers.secondaryId = ...
)Eg, if you were planning on:
where orderId in (select value from ...)
or secondaryorderid in (select value from ...)Then you make it so that you only call your subquery once, and build your OR clause into it.
where exists (select * from ...
where Customers.orderId = value
or Customers.secondaryOrderId = value
)The whole point of this is to ensure that the complicated subquery is only executed one time. That doesn't happen with a CTE, or by replacing two INs with two EXISTSs.
Code Snippets
where exists (select * ....
where Customers.orderId = ...
or Customers.secondaryId = ...
)where orderId in (select value from ...)
or secondaryorderid in (select value from ...)where exists (select * from ...
where Customers.orderId = value
or Customers.secondaryOrderId = value
)Context
StackExchange Database Administrators Q#98419, answer score: 10
Revisions (0)
No revisions yet.