question

aRookieBIdev avatar image
aRookieBIdev asked

select query with or with out union all

Hi , I have the following requirement . I need to join two tables based on condition 1 and pick field A from table2 and based on condition 2 and pick field b from table2. Please find below my query. Insert INTO TABLEB SELECT SR.COLUMNA FROM TABLEA SR LEFT JOIN TABLE B ML ON SR.COLUMNA = ML.COLUMNA UNION ALL SELECT SR.COLUMNB FROM TABLE A SR LEFT JOIN TABLEB ML ON SR.COLUMNB = ML.COLUMNA WHERE ML.COLUMNA IS NULL AND SR.COLUMNB IN NOT NULL GROUP BY SR.COLUMNA I have a doubt regarding the use of union all .Is it better to use union all or is there any better way to do THIS. I would like to mention that i have around 40 million rows .so performance is my main concern.
sql-server-2008performance-tuningunion-all
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

TimothyAWiseman avatar image TimothyAWiseman commented ·
On the top half you aren't retreiving any columns from tableB and since it is a left joing tableB won't exclude any rows from TableA. Unless a row in tablea might match to multiple rows in tableb and you want to capture those repetitions then it seems the join could be removed from that top half without affecting the results...
0 Likes 0 ·

1 Answer

·
WilliamD avatar image
WilliamD answered
The union all is basically telling the query optimizer that it doesn't need to sort and remove duplicates from both the selects. This will save you a potentially large sort operation and will result in a quicker execution when compared to a "normal" union. However, the onus is on you to ensure that the data is then "clean".
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

WilliamD avatar image WilliamD commented ·
I also don't see how the top half of the union is helping - it is taking all of TableA and joining to TableB without filtering in any way, so is redundant IMO
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.