I'm interested to know if a union is better than running multiple queries.
If so, are there times that multiple queries would be faster or preferred for other reasons?
I'm interested to know if a union is better than running multiple queries.
If so, are there times that multiple queries would be faster or preferred for other reasons?
If you use UNION ALL and don't sort the output, then the performance of UNION should be more-or-less the same as the performance of multiple separate queries assuming the queries are identical to the ones you're UNIONing together. If you sort the data, obviously you're imposing some overhead (although probably less than if you sorted in it your application). If you leave out the ALL keyword, MySQL will do the extra work of DISTINCT-ing your results. Again, this imposes extra overhead although probably less than doing it yourself.
You ask if it "is better" - I assume you are referring to "performance-wise"?
If the speed impact is minimal, you might want to prefer multiple queries to keep your code more readable; instead of dealing with multiple queries, doing different things, in one union.
Depends on the use case, for sure. But readable and understandable code might have it's worth in a bigger project in the long term