Skip to content
Fix Code Error

How to output MySQL query results in CSV format?

March 13, 2021 by Code Error
Posted By: MCS

Is there an easy way to run a MySQL query from the Linux command line and output the results in CSV format?

Here’s what I’m doing now:

mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/        /,/g' | tee list.csv
select id, concat("""<h2>Solution</h2><p>From <a href="http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/" rel="noreferrer">http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/</a></p>

<pre><code>SELECT order_id,product_name,qty
FROM orders
WHERE foo = 'bar'
INTO OUTFILE '/var/lib/mysql-files/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY 'n';

Using this command columns names will not be exported.

Also note that /var/lib/mysql-files/orders.csv will be on the server that is running MySQL. The user that the MySQL process is running under must have permissions to write to the directory chosen, or the command will fail.

If you want to write output to your local machine from a remote server (especially a hosted or virtualize machine such as Heroku or Amazon RDS), this solution is not suitable.

Answered By: Paul Tomblin

Related Articles

  • error LNK2005: ✘✘✘ already defined in…
  • Problems Installing CRA & NextJS from NPM (Error:…
  • Rails wrong number of arguments error when generating…
  • Error 'Map', but got one of type 'Null' flutter web with…
  • How to properly do JSON API GET requests and assign output…
  • Ember data parent / child models and json
  • 'block in draw' rails 6 routes
  • How does the vim "write with sudo" trick work?
  • incompatible character encodings: ASCII-8BIT and UTF-8
  • Dependent/Cascading Dropdowns in Aurelia

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

jQuery how to find an element based on a data-attribute value?

Next Post:

Set a default parameter value for a JavaScript function

Leave a Reply Cancel reply

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

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error