Export MySQL data to CSV
How to export a MySQL table or database to CSV, what each method changes (NULLs, quoting, encoding, headers), and whether the file stays usable once shared.
Exporting a MySQL table to CSV turns structured rows into delimited plain text. That is useful for spreadsheets, reporting tools and handoffs to other systems, but some meaning can change along the way. This review covers what the conversion keeps, what it alters, which export method fits which situation, and how to tell whether the resulting file will still be correct after someone else opens it.
Is CSV the right format for your purpose?
CSV is a good fit when the goal is to move tabular values into a tool that reads rows and columns, such as a spreadsheet, a BI tool, a data pipeline or another database's bulk loader. Its main benefit is reach: almost every data tool can read it, and it stays inspectable as plain text. The main tradeoff is that CSV carries only text values. Column types, NULL semantics, character encoding, constraints, indexes and relationships between tables are not part of the file. A reader has to infer them, or they have to be documented separately.
Another format is often the better choice in these cases:
- Backups or moves between MySQL servers: a SQL dump keeps schema, types and keys, and a CSV export does not.
- Data with many commas but no tabs: tab-separated output (TSV) avoids most quoting problems and is MySQL's default output style.
- Values where NULL and empty string mean different things: CSV has no standard way to mark NULL, so the receiving side must agree on a convention.
- Nested or semi-structured data such as JSON columns: CSV can hold the text, but downstream tools see only a string.
What a CSV export actually changes
The export does not change the data stored in MySQL. It produces a text representation of a query result. The differences show up in that representation:
- Types become text. Integers, decimals, dates and binary data are written as characters, and the reading application decides how to interpret them again.
- NULL needs a marker. SELECT ... INTO OUTFILE writes NULL as \N by default. The mysql command-line client writes the word NULL. Other tools may write an empty field. Each choice can be misread by the receiver.
- Delimiters inside values need protection. A comma, quote or line break inside a field must be enclosed or escaped, or the row splits incorrectly.
- Escaping style varies. MySQL's server-side export escapes embedded quotes with a backslash ("). The convention most CSV readers expect, described in RFC 4180, doubles the quote (""). This mismatch is the most common source of broken imports.
- A header row is not guaranteed. INTO OUTFILE writes data rows only. Client tools usually include column names.
- Encoding is a choice. Characters outside ASCII are only safe if the file's encoding is known and the reader uses the same one.
Export methods compared
| Method | Where the file is written | Header row | Typical requirement | Best for |
| SELECT ... INTO OUTFILE | On the MySQL server host | No (add manually) | FILE privilege; path allowed by secure_file_priv | Server-side jobs, large tables |
| mysql client in batch mode | Wherever you redirect output | Yes, unless suppressed | Only SELECT access | Quick extracts to your own machine (tab-separated) |
| mysqldump --tab | Data files on the server host, plus .sql schema files | No | FILE privilege; server-writable directory | Every table in a database at once |
| MySQL Shell util.exportTable() | Machine running Shell | Depends on options | MySQL Shell installed | Configurable dialects, including CSV |
| MySQL Workbench export | Your workstation | Optional | GUI access | Occasional manual exports |
Method 1: SELECT ... INTO OUTFILE
This is the standard SQL route. The server writes the file to its own filesystem, so on a remote or managed database the file does not end up on your computer. The account needs the FILE privilege. The target directory must be permitted by the secure_file_priv setting, and the file must not already exist.
SHOW VARIABLES LIKE 'secure_file_priv';
SELECT id, name, email
FROM customers
INTO OUTFILE '/var/lib/mysql-files/customers.csv'
CHARACTER SET utf8mb4
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\'
LINES TERMINATED BY '\n';
OPTIONALLY ENCLOSED BY quotes only string-typed columns. ENCLOSED BY quotes every column. If secure_file_priv is empty, any server-writable path is allowed. If it is NULL, file export is disabled. If it names a directory, you must write inside that directory. To control how NULL appears, wrap columns in IFNULL() or COALESCE(), for example IFNULL(email, ''). Doing so deliberately merges NULL and empty string, so only use it when that loss is acceptable.
Adding a header row
SELECT 'id', 'name', 'email'
UNION ALL
SELECT id, name, email FROM customers
INTO OUTFILE '/var/lib/mysql-files/customers.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n';
This approach has two caveats. SQL does not formally guarantee row order in a UNION without ORDER BY, so check that the first line of the file is the header. Also, because the header values are strings, the combined columns become string-typed, and numeric columns may be quoted as well.
Method 2: the mysql command-line client
Running a query in batch mode writes tab-separated output with a header line to standard output, which you can redirect to a file on your own machine. In this mode the client escapes tabs, newlines and backslashes inside values (for example, a line break becomes the two characters \n) and prints NULL as the word NULL. The --raw option turns that escaping off, and --skip-column-names drops the header.
mysql -u report_user -p --batch -e "SELECT id, name, email FROM shop.customers" > customers.tsv
A common shortcut pipes this output through a tool that replaces tabs with commas. That produces a broken file as soon as any value contains a comma or quote, because nothing gets enclosed. If the destination accepts TSV, keep the tabs. If it needs CSV, use a method that quotes fields.
Method 3: exporting a whole database with mysqldump --tab
CSV holds one table per file, so a database export means one file per table. mysqldump with --tab writes a .sql file with each table's structure and a .txt data file for each table. If you name only the database, it covers every table. The data files are written by the server through the same mechanism as INTO OUTFILE, so the FILE privilege and secure_file_priv rules apply, and the directory must be on the server host.
mysqldump -u root -p --tab=/var/lib/mysql-files \
--fields-terminated-by=, --fields-optionally-enclosed-by='"' \
--lines-terminated-by='\n' shop
The .sql files contain the schema that the CSV data lacks. Keep them with the data if anyone may need to reload it.
Method 4: MySQL Shell and Workbench
MySQL Shell offers util.exportTable(), which writes on the machine running Shell and accepts a dialect option that includes a CSV setting. MySQL Workbench can export a result grid or a table to CSV through its export wizard. Both remove the need for server file access. However, the evidence for this review does not confirm exactly how each version handles embedded quotes, NULL or encoding. Check the documentation for your version, then run the test described below before relying on either tool.
// MySQL Shell, JavaScript mode
util.exportTable("shop.customers", "customers.csv", {dialect: "csv"})
One row, two outputs
Take a row with id 7, the name O'Neil, "Pat" (which contains a comma and double quotes), and a NULL email. Method 1's settings produce the first line below. A strictly RFC 4180-style writer that represents NULL as an empty field would produce the second.
7,"O'Neil, \"Pat\"",\N
7,"O'Neil, ""Pat""",
A reader expecting doubled quotes may treat the backslash version as malformed, and it will not recognize \N as NULL. A reader expecting MySQL conventions, such as LOAD DATA with matching options, may misread the second line. Neither is wrong in isolation. They only need to match the receiver.
Will the file stay readable and usable after sharing?
Encoding: export as UTF-8 (utf8mb4 in MySQL terms) and tell recipients so. Some spreadsheet applications assume a legacy encoding when they open a CSV directly, which can garble accented letters and emoji. Using the application's import feature with the encoding set explicitly avoids this. Behavior differs between applications and versions, so one clean rendering on one machine does not prove the file is safe everywhere.
Value reinterpretation: spreadsheets often convert text that looks numeric. Leading zeros in ZIP codes or account numbers can disappear. Long identifiers can lose precision or switch to scientific notation. Date-like strings can be reformatted. None of this is caused by the CSV file. It happens when the file is opened. If those columns matter, import them as text or warn recipients.
Formula injection: a cell beginning with =, +, - or @ may be treated as a formula by spreadsheet software. If exported data includes user-supplied text and the file will be opened in a spreadsheet, review or neutralize those values before sharing.
Line endings and delimiters: MySQL writes \n line endings unless told otherwise. RFC 4180 describes \r\n, though many readers accept either. In some locales, spreadsheet software expects semicolons rather than commas, which matters if the file goes outside the US.
Accessibility, search and editing: a CSV is plain text, so it can be searched, diffed and edited in any text editor, and it contains no visual styling that assistive technology would have to interpret. The structure a screen reader user depends on comes from the header row and clear column names, so include both. The evidence here does not cover how specific screen readers present CSV files in specific applications.
Before you send the file
- Export a small test set that includes a comma, a double quote, a line break, a non-ASCII character and a NULL, then open it in the actual destination tool.
- Confirm the header row is present and comes first.
- Agree with the recipient on the NULL marker, the quote escaping style and the encoding.
- Check that identifier-like columns keep their leading zeros and full length.
- For database-wide exports, keep the schema files alongside the data.
Gaps in this review
No test results, version-specific measurements or product documentation excerpts were supplied for this review. The behavior described reflects general, documented MySQL conventions. Version-specific details, especially for MySQL Shell, Workbench and particular spreadsheet or assistive technology products, should be checked against current documentation and a scoped test in your own environment.