UNION ALL
is literally one of the cheapest operations that exists in SQL Server. It simply takes the result sets from each candidate query and concatenates the results. UNION
is different, it needs to perform a DISTINCT
sort, but if you are using UNION ALL
then I can guarantee you that the concatenation itself is not the problem.
There are a few reasons why your query might be performing poorly:
The underlying queries being concatenated are inefficient, due to poor indexing or other factors. Post the execution plan.
You're applying the UNION ALL
before the predicates, i.e. assuming that UNION ALL
obeys the distributive law (it doesn't). This turns a simple post-concatenation into a table concatenation and very expensive table scan.
The plan itself is not slow, but you are selecting a huge number of results. If so, then there's not much you can do other than to try to limit the result size (normalize?).
Edit - I just reread the question and noticed this line:
We do a union all of the similar data inside a view
The problem is definitely #2 - what you're essentially doing is concatenating the entire tables and then applying predicates, which destroys any chance the optimizer might have had of effectively using any indexes on the underlying tables. Every query will end up as 5 expensive table scans.
The only way you're going to solve this is by either materializing the view (which you say you can't do) or getting rid of it and substituting a stored procedure or UDF. You need to treat individual tables individually for best performance; concatenating them all together and trying to query against the concatenated results will always be (very) slow.