Try running this query in SQL Server Management Studio with the actual execution plan enabled. See if internal choices will look for an index on these keys.
I set up a test case with three tables that had an ID as a clustered primary key. The execution plan showed queries with a clustered index for the three selected identifiers.
However, if you really want internal queries to optimize their plans this way, you can put a WHERE clause for each subquery. For instance:
select * from ( select Id from table1 where Id in (1,2,3) union all select id from table2 where Id in (1,2,3) union all select id from table3 where Id in (1,2,3) ) as X
Also note that the above union all will potentially return duplicates if more than one of the tables has a matching Id . If this is a problem, you can change union all to just union like this.
select * from ( select Id from table1 where Id in (1,2,3) union select id from table2 where Id in (1,2,3) union select id from table3 where Id in (1,2,3) ) as X
I cannot guarantee this behavior in other database systems, but I would be surprised if their query optimizers did not do the same.
source share