MySQL output query to file

Book page

Ways to output the results of a MySQL query to a file:

  1. Use the command line switch option -e to input the query and > to redirect the output to a file:
    % mysql -uuser -ppass -e "SELECT id, name FROM person WHERE name like '%smith%'" database > smiths.txt
    
  2. Use the SQL query construct INTO OUTFILE 'filename' to write the results to file from inside the MySQL command line interface:
    % mysql -uuser -ppass database
    mysql> SELECT id, name INTO OUTFILE '/tmp/smiths.txt' FROM person WHERE name like '%smith%';
    Query OK, 10 rows affected (0.01 sec)
    

    Be sure where you have write permissions where the output file will be written to. Specify the full path if in doubt.