简体   繁体   中英

UNION / UNION ALL slow or not working

I have two tables full of customer survey response data. I've been running queries on them separately that return results in less than one second, but if I union them it seems to run forever. After 5+ minutes no results are returned yet and no errors have been thrown, it's still apparently "running" but I can't figure out what it's actually trying to do that could be so complicated.

In essence, my queries that work separately are:

SELECT
oldsurveys.column1 as [something1],
oldsurveys.column2 as [something2],
oldsurveys.column3 as [something3],
'staticvalue1' as [something4],
oldsurveys.column5 as [something5]
FROM
database1.dbo.table1 oldsurveys
WHERE
oldsurveys.column1 = 'something'
AND oldsurveys.column2 >= '2014-01-01 00:00:00'
ORDER BY [something2], [something1]

SELECT
newsurveys.column1 as [something1],
newsurveys.column2 as [something2],
newsurveys.column3 as [something3],
newsurveys.column4 as [something4],
'staticvalue2' as [something5]
FROM
database2.dbo.table1 newsurveys
WHERE
newsurveys.column1 = 'something'
AND newsurveys.column2 >= '2014-01-01 00:00:00'
ORDER BY [something2], [something1]

If I run this, I get two tables of data returned almost instantly. If I add UNION ALL between the two select statements, comment out the first ORDER BY and try running again it just runs and runs and runs, no results...

Any idea what I'm doing wrong? Would the tables being in different databases cause this, and if so, is there a workaround?

Without an execution plan, getting the exact cause of your performance problem is nearly impossible. Here's one possible explanation for this behaviour:

  • you've got indices on [something2] and [something1] for both tables
  • when you query each table separately, SQL Server uses the indices
  • when you UNION ALL both queries, SQL Server could theoretically use each index to sort the results of the subquery, but it cannot use the index to sort the complete result set, so it has to sort the complete result set

BTW, (since you mentioned both in your title but only one in your post body), there's a huge difference between UNION and UNION ALL - the former might perform much worse, since it has to remove duplicates from the result set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM