EmergencyEMERGENCY? Get 24/7 Help Now!


 | September 14, 2011 |  Posted In: Insight for Developers, MySQL


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.

Jervin Real

As Senior Consultant, Jervin partners with Percona's customers on building reliable and highly performant MySQL infrastructures while also doing other fun stuff like watching cat videos on the internet. Jervin joined Percona in Apr 2010.

Leave a Reply


Percona’s widely read Percona Data Performance blog highlights our expertise in enterprise-class software, support, consulting and managed services solutions for both MySQL® and MongoDB® across traditional and cloud-based platforms. The decades of experience represented by our consultants is found daily in numerous and relevant blog posts.

Besides specific database help, the blog also provides notices on upcoming events and webinars.
Want to get weekly updates listing the latest blog posts? Subscribe to our blog now! Submit your email address below and we’ll send you an update every Friday at 1pm ET.

No, thank you. Please do not ask me again.