Save MySQL query results into a text or CSV file

Source: Internet
Author: User
Save MySQL query results into a text or CSV file

Posted by Quinn McHenry in MySQL

MySQL provides an easy mechanism for writing the results of a SELECT statement into a text file on the server. using extended options of the into OUTFILE nomenclature, it is possible to create a comma separated value (CSV) which can be imported into a spreadsheet
Application such as OpenOffice or Excel or any other applciation which accepts data in CSV format.


Given a query such

Select order_id, product_name, qty from orders

Which returns three columns of data, the results can be placed into the file/TMO/orders.txt using the query:

Select order_id, product_name, qty from orders
Into OUTFILE '/tmp/orders.txt'

This will create a tab-separated file, each row on its own line. To alter this behavior, it is possible to add modifiers to the query:

Select order_id, product_name, qty from orders
Into OUTFILE '/tmp/orders.csv'
Fields terminated ','
Enclosed '"'
Lines terminated by '\ N'

In this example, each field will be enclosed in "double quotes," the fields will be separated by commas, and each row will be output on a new line separated by a newline (\ n ). sample output of this command wowould look like:

"1", "tech-recipes sock puppet", "14.95" "2", "tech-recipes chef's hat", "18.95"
...

Keep in mind that the output file must not already exist and that the user MySQL is running as has write permissions to the directory MySQL is attempting to write the file.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.