November 27, 2014


Here’s a quick tip I know some of us has overlooked at some point. When doing SELECT … UNION SELECT, where do you put the the INTO OUTFILE clause? On the first SELECT, on the last or somewhere else? The manual has the answer here, to quote:

Only the last SELECT statement can use INTO OUTFILE. (However, the entire UNION result is written to the file.)

However, I still see queries going further lengths to the same effect. For example, putting the UNIONs into a subquery and then doing the SELECT INTO OUFILE from this. Using the employees.employees table:

Compared to using UNION simply:

You will notice the second query without the additional derived <derived2> table holding all the results from the UNION queries, making the latter more performant than the former. Of course you can stil break all this UNION queries down and SELECT them INTO OUTFILE separately, then concatenate the resulting files offline if you think the number of resulting rows would be to big to bear, otherwise SELECT .. UNION SELECT INTO OUTFILE should be convenient.

Lastly to demonstrate the purpose of this post.

About Jervin Real

Jervin is a member of Percona's Rapid Response Consulting team. When you come to Percona for consulting, chances are he'll be greeting you first. His primary role is to make sure customer issues are handled efficiently and professionally. Jervin joined Percona in April 2010.

Speak Your Mind