views:

62

answers:

4

I have a sql function that returns a table. The table is populated via 6 or so reasonably complex statements.

Is it better to UNION together these statement so there is only 1 insert or are these better kept separate?

Or does it make no difference whatsoever?

+1  A: 

Within a User Defined Function, I don't see a reason to use one over the other. A UNION has the potential to be more constraining than separate statements...

I'd like to see the details of the function, and it's use, because it's possible it might not be necessary at all.

OMG Ponies
it IS possible to do this in a single insert without the unions but it's incredibly messy (trust me, I've had a go)
Chris Simpson
+2  A: 

I'd just UNION ALL them - the key there is not a UNION (which could be less efficient by deduping), but a UNION ALL.

AdaTheDev
ahh, the union all, that is a good point
Chris Simpson
+1  A: 

Instead to think by yourself what is the best solution i suggest as a tip to use a properly tool.

In SQL server using the Managment Studio you can evaluate the performance by Display Estimated Execution Plan. So in this way you can really see the differences between your 2 cases and select the best one by observing the results.

Luka
+1  A: 

Actually, it does make a difference.

When you have separate INSERTs, you have to take care to do it inside a transaction, so that you have a consistent state at all times. But, since they're separate, the amount of memory required for the server to complete is less because every INSERT has it's own result set - when the query completes the server is free to perform another query etc...

When you have everything inside one big query joined by UNION ALL the server would need more temp tables and more memory to complete. But, this way you have something of a 'bulk' insert, and could result in faster insert.

Personally, I'd go with separate inserts inside a transaction. Sometimes just by having something done simpler is way more beneficial in terms of maintainability and debugging than some minor performance gain (if any, depends on the number of rows actually getting inserted)

veljkoz
you might disagree but in this case I don't believe I need transactions. no data is being updated as a result of these statements, only presented to a user so if a record changes before the whole thing is complete that does not matter to me. Thanks for the input though.
Chris Simpson
Ok, that's one more reason for separate inserts because transactions don't apply it would be even faster...
veljkoz
I agree with this. In my experience, a UNION can unnecessarily slow down an insert process because of the time (and memory) it takes to create the union in the first place. And often transactions can still be wrapped around separate inserts, even when needed. I would go with the separate inserts, if we are speaking purely server side database work.
sql_mommy