Icerock's Blog Code snippets, useful tips, experiences and a bit of help :o)

5Nov/100

SELECT … UNION … INTO OUTFILE

Versión en Español

Quick Tip:

Sometimes you need to dump some data directly to a file.
That's easy by issuing a SELECT ... INTO OUTFILE .... FROM ...

But what happens when you need to retrieve data from in some particular way or when you want to add "headers" to the columns you're outputting?
Likely you'll get an error that UNION statement is not allowed to play with INTO OUTFILE.

So this is the way to output data with UNION:

SQL:
  1. SELECT *
  2.   INTO OUTFILE '/dir/to/file.csv'
  3.   FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '"'
  4.   LINES TERMINATED BY '\r\n'
  5. FROM (
  6.   ( SELECT 'FieldA','FieldB','FieldC','FieldD' )
  7.   UNION
  8.   ( SELECT FieldA, FieldB, FieldC, FieldD FROM my_table)
  9. ) AS T

In that way you're making a compound table from the UNION statement. Then, you select * from that table to the outfile.
Remember to ALWAYS give an alias to a derived table :)

Happy Dumping!

Filed under: English, MySQL Leave a comment