Use of Sub-Selects
- When you need to further test each processed record in the Where clause for meeting an additional condition, AND that condition can NOT be checked directly on the Where clause level, you probably need a sub-select.
- As it is performed once for each outer level record it is considered as quite an expensive tool. Therefore, if the criteria checked in a sub-select can be moved to the outer where clause level, it is preferable. If you still need to use a sub-select, it is very important to restrict the outer where clause population to the very minimum possible so that lesser records would need to be further checked for the sub-select condition.
- When no value needs to be returned from the sub-select query but rather simply use it to
check if a certain condition is true or false, use the EXISTS function as follows:
Select ... From ... Where ... AND EXISTS (<sub-select>)
- A sub-select query may refer to any value of the outer level record as its input parameters. Notice that if your sub-select does NOT refer to any of the processed record fields, it means that the result set of the sub-select would be the same for ALL the processed records.
- Note that this could, but not necessarily, be an indication that your sub-select is set up wrong. One case where it is definitely wrong is when the sub-select result is input to an EXISTS function.