Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: using UNION vs multiple queries

Tags:

mysql

union

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?

like image 872
Yehosef Avatar asked Oct 20 '10 15:10

Yehosef


People also ask

Are unions slow SQL?

The main reason for the union sql running slower is that a union causes mysqld to create an internal temporary table. It creates just a table for a UNION ALL and a table with an index (to remove duplicates) for a UNION DISTINCT. Hope this helps.

Is UNION efficient in SQL?

UNION ALL is faster than UNION because plain UNION is expecting that within two joined datasets are duplicates which need to be removed. If you can ensure (by inner WHERE clauses) that there will be no duplicates, it's far better to use UNION ALL and let database engine optimize the inner selects.

Is it preferable to use UNION all instead of UNION in a query?

A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.

Is UNION faster than join?

Union will be faster, as it simply passes the first SELECT statement, and then parses the second SELECT statement and adds the results to the end of the output table.


1 Answers

  • 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 UNION-ing together.
  • If you use UNION ALL and 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.
like image 58
Larry Lustig Avatar answered Sep 23 '22 21:09

Larry Lustig