Performance Question on Unions vs multiple inserts in temp table

  • I have a stored procedure that I can either use serveral unions and return the data in 1 query or create a temp table and insert each one of the query results and then return the temp table. I always heard unions were slow but during my tests it appears the union method is faster. Just looking for some input.

    Thanks!

    Kurt

  • It all depends on the type of union.

    If it is a union ALL without an order by, the union will be faster, as the server will not need to use a Worktable. If not, the server will use a Worktable to do the distinct or the order by, and this means it will do more or less the same as you are doing when you use a temp table ( better : use a table variable ).

     

    Bert

  • I would definately recommend going with the unions. A logical union is not slow in any way, however the implementation requires a distinct operation to remove any duplicates. Like Bert said, if you know that the inputs to the union does not contain duplicates you can help the optimizer by executing a UNION ALL instead.

  • thanks for the replies.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply