[MySQL] Execute Queries from Command Line and Output to CSV File
This article introduces how to execute MySQL queries from Linux CLI and output the results to a CSV file.
The command to execute MySQL queries and output to CSV file is as follows:
mysql -u [username] -p -h [host] [dbname] -e "[query to execute]" \\
| sed -e 's/\ /,/g' \\
> [Output CSV file path]
Process explanation:
Sample command with headers in the first row:
mysql -p test -e \\
"select utm_campaign, count(*), sum(num_purchase) from customers where utm_campaign = 'hoge';" \\
> output.csv
Sample command without headers in the first row. Use the -N option to suppress header display.
mysql -u [username] -p -h [host] [dbname] -N -e \\
"select utm_campaign, count(*), sum(num_purchase) from customers where utm_campaign = 'hoge';" \\
| sed -e "s/\ /,/g" \\
>> output.csv
That’s all from the Gemba on saving MySQL query execution results to CSV files.