Check if any of the values is in a subquery result 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:

 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?
Try:

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.