MySQL Export Table to CSV
Exporting data from MySQL to a CSV (Comma-Separated Values) file is a common task, useful for data analysis, backup, or transferring data to another system.
1. Export Table to CSV Using SELECT ... INTO OUTFILE
The simplest way to export a MySQL table to CSV is by using the SELECT ... INTO OUTFILE statement.
Syntax:
Example:
Key Points:
✔ FIELDS TERMINATED BY ',' → Specifies column separation using commas.
✔ ENCLOSED BY '"' → Wraps each field in double quotes (to handle text with commas).
✔ LINES TERMINATED BY '\n' → Each row is written to a new line.
✔ The file is saved in MySQL's data directory (/var/lib/mysql-files/ by default).
⚠ Permissions Issue?
Ensure MySQL has permission to write to the output directory. Use:If
secure_file_privis set to a directory, save your file there.
2. Export Table to CSV Using mysqldump Command (CLI)
Another way to export a MySQL table to CSV is by using the mysqldump utility.
Command:
This exports the table as .txt and .sql files in the specified folder.
3. Export MySQL Query to CSV Using INTO OUTFILE
You can export a custom query result instead of the entire table.
Example:
4. Export MySQL Table to CSV Using UNION ALL for Column Headers
Since OUTFILE doesn’t include column headers, use UNION ALL to manually add them.
5. Export Table to CSV Using MySQL Workbench
Steps:
- Open MySQL Workbench.
- Go to Server > Data Export.
- Select your database and table.
- Choose CSV format.
- Click Start Export.
6. Export MySQL Table to CSV Using csv Command in Linux
For a quick export, use:
Summary
| Method | Pros | Cons |
|---|---|---|
SELECT ... INTO OUTFILE | Fast, direct export | Requires file permissions setup |
mysqldump --tab | Exports multiple tables | Only works on local servers |
| MySQL Workbench | User-friendly GUI | Slower for large tables |
Linux mysql command | Quick command-line export | Requires additional formatting |
Would you like help automating this process? š

