Offline, your approach seems to be the only approach in standard SQL.
You will greatly improve performance by changing UNION to UNION ALL . UNION must read data from both tables and then delete duplicates before returning any data.
UNION ALL does not eliminate duplicates. How much better this is done depends on the database engine and, possibly, on the rotation of the parameters.
Actually, there is one more possibility. I don't know how well this works, but you can try:
select * from ((select const.tableName, a.* from A cross join (select 'A' as tableName where x.TableName = 'A') ) union all (select const.tableName, b.* from B cross join (select 'B' as tableName where x.TableName = 'B') ) ) t
No promises. But the idea is to cross join a table with 1 or 0 rows. This will not work in MySQL because it does not allow WHERE clauses without FROM . In other databases, you may need a scoreboard, such as dual . This allows the query engine to fully optimize the reading of the table when there are no records in the subquery. Of course, just because you give an SQL engine, the possibility of optimization does not mean that it will be.
Also, "*" is a bad idea, especially in a union. But I left him, because this is not at the center of the issue.
source share