Are you having difficulty performing MySQL export to CSV operation because there is too much confusion? You have just landed at the right post. We give you an easy, stepwise guide in 5 different ways to do just that.

MySQL is offered in two different editions: the open-source MySQL community server and the proprietary Enterprise server. However, only a limited number of applications support the raw format of MySQL export tables. Therefore, it is often beneficial to export MySQL tables to CSV format.

A CSV File: What It Is and Why We Use It

CSV is a standard and lightweight format with several benefits, such as its simplicity, flexibility, and compatibility with various applications. Their straightforward structure makes them widely used across various industries. We need to use CSV for the following reasons:

  • Store tabular data like spreadsheets and databases.
  • Easily transfer data between different applications and systems.
  • Import and export data in many software programs.
  • Organize and manipulate data sets for analysis.
  • Ideal for creating backups and archiving data due to their simplicity.

Methods to Perform MySQL Export to CSV

Database administrators and developers commonly export MySQL tables to CSV files. In this guide, we share five different methods for doing so. These methods include using command-line tools such as mysqldump and graphical user interfaces such as phpMyAdmin and MySQL Workbench.

Each method has advantages and disadvantages, and the choice of which method to use largely depends on the specific requirements of the task. By following the steps outlined in this guide, you will be able to successfully perform MySQL output to CSV file format, regardless of the method you choose.

Migrate your MySQL Data Within Minutes!

Migrating your data from MySQL doesn’t have to be complex. Try Hevo and go for a seamless migration using Hevo’s no-code platform. With Hevo, you can:

  1. Effortlessly extract data from MySQL and other 150+ connectors
  2. Tailor your data to your destination’s needs with features like drag-and-drop and custom Python scripts.
  3. Achieve lightning-fast data loading, making your data analysis ready.

By incorporating Hevo, you can see why customers like Slice and Harmoney have upgraded to a powerful data and analytics stack

Get Started with Hevo for Free

1. Using Command Line

It is extremely easy to use the command line to perform MySQL export to CSV. You do not need to download any additional software. We also wrote an in-depth article on the MySQL export database command line.

You will also learn how to perform MySQL export to CSV using the command line under the following conditions:

To be able to perform MySQL export to CSV, you need to ensure that the directory you are using has write permission granted to it.

To migrate your data from MySQL to CSV using the command line, you can run the following command:

SELECT *
INTO OUTFILE '/var/lib/mysql-files/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM test;
  • This query exports all data from the test table into a CSV file.
  • The CSV file is saved to /var/lib/mysql-files/orders.csv.
  • Each field in the CSV is separated by a comma and enclosed in double quotes.
  • Each field value is enclosed in double quotes (") to handle any special characters.
  • Each row of data in the CSV ends with a newline character (\n) to ensure proper line breaks.

After running this command, you will see something like this displayed on your screen:

SQL query output
  • Make sure to use the .csv extension for your output file.
  • The ORDER clause can arrange the data according to a particular attribute.
  • The LIMIT clause restricts the number of rows copied into the output file.

a. Exporting Selected Columns of a Table

  • To do this you can use the SELECT statement to specify the columns you want to export.
  • You may additionally use the WHERE clause to use specific conditions and filter the results.
SELECT columnName, ….
FROM tableName
WHERE columnName = 'value';

b. Exporting Tables with a Timestamp

You may want to add a timestamp to the exported file, to do that you must use a MySQL prepared statement.

Use the following command to export to a CSV file and add a timestamp for the time the file was created:

SET @TS = DATE_FORMAT(NOW(),'_%Y_%m_%d_%H_%i_%s');
SET @FOLDER = '/var/lib/sql-files/';
SET @PREFIX = 'employees';
SET @EXT    = '.csv';
SET @CMD = CONCAT("SELECT * FROM tableName INTO OUTFILE '",@FOLDER,@PREFIX,@TS,@EXT,
"' FIELDS ENCLOSED BY '"
' TERMINATED BY ',' 
ESCAPED BY '"'",
"LINES TERMINATED BY 'n';");
PREPARE statement FROM @CMD;
EXECUTE statement;
  • The query creates a timestamp variable @TS to format the current date and time for use in the file name.
  • It sets the folder path @FOLDER where the CSV file will be saved.
  • The variable @PREFIX defines the beginning of the file name as “employees.”
  • The variable @CMD constructs a SQL command that exports data from tableName into a CSV file, using the defined path, prefix, timestamp, and extension.
  • Finally, it prepares and executes the SQL statement, resulting in the data being exported to a file named like “employees_YYYY_MM_DD_HH_MM_SS.csv”.

c. Export with Column Headers

It is often convenient to add column headers to the output file to better identify and analyze the data. To do this, you must use the UNION statement.
Use the following command to add column headers:

(SELECT 'columnHeading', ...)
UNION
(SELECT column, ...
FROM tableName
INTO OUTFILE 'path-to-file/outputFile.csv’'
FIELDS ENCLOSED BY '"' 
TERMINATED BY ','
ESCAPED BY '"'
LINES TERMINATED BY 'n')
  • The first SELECT adds a row of column headings for the output file.
  • The UNION merges the headings with the data from the second SELECT.
  • The second SELECT exports data from tableName to a CSV file at 'path-to-file/outputFile.csv'.
  • Fields are enclosed in double quotes ("), separated by commas (,), with special characters escaped by a double quote.
  • Each data row in the CSV ends with a newline character (n).

d. Handling NULL Values

If your results contain NULL values, they will appear as ‘N’ in the exported file instead of NULL. This may lead to confusion and thus, you may want to replace this ‘N’ string with a string like NA (not applicable) that makes more sense.
Use the following command to do it:

SELECT column, column, IFNULL(column, 'NA')
FROM tableName INTO OUTFILE 'path-to-file/outputFile.csv'
FIELDS ENCLOSED BY '"'
TERMINATED BY ','
ESCAPED BY '"' 
LINES TERMINATED BY 'n');
  • This query retrieves specified columns from tableName, including a third column that replaces any NULL values with ‘NA’.
  • The results are exported to a CSV file located at 'path-to-file/outputFile.csv'.
  • Each field in the CSV is enclosed in double quotes ("), separated by commas (,), and special characters are escaped by a double quote.
  • Each row of data in the CSV ends with a newline character (n).
Migrate your data from MySQL to Snowflake
Migrate your data from MySQL to BigQuery
Migrate your data from MySQL to Databricks

2. Using mysqldump

mysqldump is a utility tool provided by MySQL server that enables users to export tables, databases, and entire servers. Moreover, it is also used for backup and recovery. Here, we will discuss how mysqldump can be used to perform MySQL export to CSV.

  • Use the following command in a command prompt/terminal:
mysqldump -u [username] -p -t -T/path/to/directory [database] [tableName] --fields-terminated-by=,
  • The given command will create a copy of the table specified by tableName at the location you define using the -T option.
  • The file’s name will be the same as that of the table and will have a .txt extension. This marks the completion of MySQL export to CSV operation using mysqldump.

3. Using MySQL Workbench

MySQL Workbench provides an Import/Export Wizard which allows you to export our database/ tables to a specified format using a graphical user interface. The wizard supports JSON and CSV formats to be able to seamlessly perform MySQL export to CSV operation.

To download MySQL Workbench.

You can follow the given simple steps to operate MySQL export to CSV data transfer.

Step 1

  • Use the left bar “schemas” tab to locate the table you want to export.

In this example, we will be exporting the employee’s table in the classic model’s database.

MySQL Workbench- Locating Table
Image Source

Step 2

  • Right-click using your mouse on the table and select “Table Data Export Wizard” to get the following screen.
  • Select the columns you want to export.
MySQL Workbench- Selecting Columns to Export
Image Source

Step 3

  • Click on Next.
  • Browse to the directory where you want to save the output file.
  • Choose the CSV format option.
MySQL Export to CSV Format- MySQL Workbench
Image Source

Step 4

  • Click on Next.
  • Your data will start exporting.
  • You can track the process through the logs.

 4. Using phpMyAdmin

phpMyAdmin provides a graphical user interface to export your MySQL table in different formats. Apart from CSV, it supports other formats such as XML, JSON, YAML, and many others. Using phpMyAdmin your users can output your tables in MySQL to CSV files, as depicted in the steps below.

To download phpMyAdmin.

To use phpMyAdmin to export data, follow these steps:

Step 1

  • Log in to phpMyAdmin using a user that has required permissions.
  • Navigate to the database which contains the source table as shown.
phpMyAdmin Home Interface: MySQL Export to CSV
Image Source

Step 2

  • Choose the table from the database.
  • Click on Export in the top bar.
phpMyAdmin Export Option: MySQL Export to CSV

Step 3

  • Choose the CSV format from the format dropdown menu. This marks the completion of MySQL export to CSV operation.
MySQL export to CSV - phpMyAdmin
  • Click on Go.
  • Select the save file option when prompted. This step will export your MySQL to CSV format for seamless data integration and analysis.

5. Using CSV Engine

The CSV storage engine stores data in text files using comma-separated values format and is always compiled into the MySQL server. It is important to note that this method to perform MySQL export to CSV can only be used if the table does not have an index or an AUTO_INCREMENT constraint.

ALTER TABLE tableName ENGINE=CSV;

This command changes the database’s format to CSV. It can then be easily copied to another system. Before wrapping up, let’s also examine the use of CSV.

Why Export Data from a MySQL Database into a CSV File?

Exporting data from a MySQL database into a CSV file offers several advantages that make data management and analysis easier and more efficient. A few key benefits are:

  • They are compatible with other applications and systems, hence enabling easy transfer of data between them.
  • They make it easier to import data into analysis applications like Excel, R, or Python.
  • Simple backup of data. 
  • Portable. 
  • Easy export with minimal technical knowledge required. 
  • CSV files are also easily incorporated into other systems for reporting and visualization.
  • It is good for long-term data archiving.

Helpful Resources on MySQL Export to CSV

Conclusion

  • Finally, you have learned five methods to perform MySQL export to CSV. If you are comfortable writing queries, using the command line or mysqldump utility tool will be the simplest.
  • However, if you are not confident with your querying skills, MySQL export to CSV command line using MySQL Workbench and phpMyAdmin will be your best bet. 

Extracting complex data from diverse data sources such as MySQL can be challenging, and this is where Hevo comes in handy! Sign up for Hevo’s 14-day free trial and explore more such migrations.

FAQ on MySQL Export to CSV

How to export MySQL data to CSV?

1. Using MySQL Command-Line Tool (mysql)
2. Using MySQL Workbench

How do I export MySQL query to excel?

1. Execute your SQL query in MySQL Workbench.
2. Right-click on the result grid.
3. Select “Export” > “Export Results to Excel”.
4. Follow the wizard to save the query result as an Excel (.xlsx) file.

How to export a MySQL database?

1. Export Database to SQL Dump
mysqldump -u username -p database_name > database_name_backup.sql
2. Export Database to SQL Dump with Data Only
mysqldump -u username -p –no-create-info database_name > database_name_data_only.sql
3. Export Database to SQL Dump with Schema Only
mysqldump -u username -p –no-data database_name > database_name_schema_only.sql

Shruti Garg
Technical Content Writer, Hevo Data

Shruti brings a wealth of experience to the data industry, specializing in solving critical business challenges for data teams. With a keen analytical perspective and a strong problem-solving approach, she delivers meticulously researched content that is indispensable for data practitioners. Her work is instrumental in driving innovation and operational efficiency within the data-driven landscape, making her a valuable asset in today's competitive market.