SQL query results to CSV

Multiple times we get requests in projects to generate reports from database.

Below command will be helpful in exporting the MySQL query results directly into CSV (comma separated values) file

mysql -h {hostname} -u {username} -p {database_name} -B -e "SELECT code AS 'Coupon Codes' FROM salesrule_coupon WHERE rule_id=112" | sed "s/\t/,/g" > /tmp/coupon_code_$(date +%F).csv

Above command will directly export the results of the query specified to a CSV file inside the directory path specified.

Hope it is helpful.

Leave a Reply

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

Scroll to top