say we have the following SQL:
select * from (
select Id from table1
union all
select id from table2
union all
select id from table3
) as X where Id in (1,2,3)
Is the SQL optimizer smart enough to apply “where id in (1,2,3)” to each table before doing the union? Can we make an assumption about other DB vendors such as Oracle on this? Assumptions are always dangerous, but, thought I’d ask anyway.
Try running this query in SQL Server Management Studio with Include Actual Execution Plan enabled. See if the inner selects do an index seek on these keys.
I setup a test case with 3 tables that had ID as their clustered primary key. The execution plan did show clustered index seeks on the three IDs selected.
However, if you really want to be sure the inner queries optimize their plans this way, you can put a WHERE clause on each sub-query. For example:
Also note that the above
union allwill potentially return duplicates if more than one of the tables have a matchingId. If this is a problem, you can changeunion allto justunionlike so.I cannot guarantee that behavior on other DB systems, but I’d be surprised if their query optimizers didn’t do the same thing.