SQL Query to CSV

The post assume the MySQL database, syntax may vary for other databases.

Sometime we need to send the actual data of the table but in a format that is easy to read for the received. If we sent the database backup, the received must create a database to read the data.

So for method to export that with technology or database neutral format is to export it as Command Separate Version aka CSV format. The default command produced the .txt file with <tab> as filed values splitter. Here it command:

SELECT * from students INTO OUTFILE 'd://students_list.txt'

But if you want to produce the file with CSV, you just need to pass a few parameters to instructor the software how to create the CSV file, lets first see the query:

SELECT * from students 
INTO OUTFILE 'd://students_list2.txt'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'

See we have terminated fields with comma (,) an have enclosed the fields with doubel quotes (") so that if there exist a field that has comma as its content, we could get the real data.

I assume you are already connected to database where students table exist.

Comments