I have a complex SQL query that can be simplified to the below:
Select ColA,ColB,ColC,ColD
From MyTable
Where (ColA In (Select ItemID From Items Where ItemName like '%xxx%')
or ColB In (Select ItemID From Items Where ItemName like '%xxx%'))
As you can see, the sub-query appears twice. Is the compiler intelligent enough to detect this and gets the result of the sub-query only once? Or does the sub-query run twice?
FYI, table Items has about 20,000 rows and MyTable has about 200,000 rows.
Is there another way to re-write this SQL statement so that the sub-query appears/runs only once?
Update: The Where clause in the main query is dynamic and added only when needed (i.e. only when a user searches for 'xxx'). Hence changes to the main select statement or re-structuring of the query are not possible.
OR
statement, the first sub-query runs and only if ColA is not there the second query runs. Anyway compiler is not intelligent enof to identify the logic of subquery – Pine