SELECT UNION Results INTO OUTFILE

PREVIOUS POST
NEXT POST

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.

PREVIOUS POST
NEXT POST

Leave a Reply

Your email address will not be published. Required fields are marked *