Export a MySQL table to CSV with column names

How to export a MySQL table to CSV or TSV with a header row, what each method changes about your data, and what to check before you share the file.

MySQL has several ways to write table data to a delimited text file, but they handle column names differently. The server-side SELECT ... INTO OUTFILE statement writes only data rows, so you have to add the header yourself. The mysql command-line client in batch mode prints a header row by default, but its output is tab-separated rather than comma-separated. This review covers which approach fits which situation, what each one does to your data, and what to check before you hand the file to someone else.

Which method should you use?

Start with where you need the file and what access you have. INTO OUTFILE is fast and runs entirely inside the server, but it writes to the database server's own filesystem and needs extra privileges. The client approach writes to whichever machine you run the client on and needs only normal SELECT access, but it produces TSV with MySQL's own escaping rules. A graphical tool such as MySQL Workbench is the simplest choice for occasional, small exports.

Method | Header row | Default delimiter | Where the file lands | Main constraint
SELECT ... INTO OUTFILE | Not written; add it with UNION ALL | Tab unless you set FIELDS options | Database server host | Needs the FILE privilege; limited by secure_file_priv
mysql client with --batch | Written by default | Tab | Machine running the client | Uses MySQL escaping, not CSV quoting
MySQL Workbench export | Usually included; confirm in the export options | Configurable | Local machine | Manual and less practical for very large or scheduled exports
mysqldump --tab | Not written | Tab unless you set options | Server host for the data files | Same server-side file restrictions as INTO OUTFILE

In short, use INTO OUTFILE with a UNION header when you can write to the server and want a true comma-delimited file. Use the client's batch output when you only have remote query access and TSV is acceptable, or when you plan to convert it with a CSV-aware tool. If the recipient only needs to read a few rows, a plain-text query result or a formatted table in a message may serve them better than any file.

Method 1: INTO OUTFILE with a header row

INTO OUTFILE has no option for column names. The common workaround is to select the names as string literals and combine them with the data using UNION ALL. Replace the table, column and path names below with your own.

SELECT 'id', 'name', 'email'
UNION ALL
SELECT id, name, email
FROM customers
INTO OUTFILE '/var/lib/mysql-files/customers.csv'
CHARACTER SET utf8mb4
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n';

To avoid typing column names by hand on a wide table, you can generate the header list from the information schema and paste the result into the first SELECT:

SELECT GROUP_CONCAT(CONCAT('''', COLUMN_NAME, '''') ORDER BY ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'your_database'
  AND TABLE_NAME = 'customers';

Practical limits to check before relying on this method:

  • The file is created on the database server, not on your workstation. With a managed or remote database you may not be able to retrieve it.
  • Your account needs the FILE privilege.
  • The secure_file_priv setting can restrict exports to one directory or disable them entirely. Check it with SHOW VARIABLES LIKE 'secure_file_priv';
  • MySQL will not overwrite an existing file, so remove or rename the old export first.
  • If you sort the data, put the data SELECT and its ORDER BY in parentheses. SQL does not guarantee row order across a UNION, so open the output and confirm the header is on the first line.
  • The placement of the INTO clause has changed across MySQL versions. Check the documentation for your server version if the statement is rejected.

Method 2: The mysql client in batch mode

Running a query with the --batch (or -B) option prints results as tab-separated rows, with column names on the first line. Redirect that output to a file:

mysql --batch -u your_user -p -e "SELECT * FROM your_database.customers" > customers.tsv

The header comes for free, and you only need ordinary query access. The output is TSV, though, not CSV. In batch mode the client escapes special characters inside values, so a tab becomes \t, a newline becomes \n and a backslash becomes \. NULL values appear as the word NULL. The --raw option turns off that escaping, but then embedded tabs or newlines in your data will break the row and column structure. The --skip-column-names option removes the header, which is the opposite of what you want here.

If you need CSV, convert the TSV with a tool that understands quoting. A simple find-and-replace of tabs with commas is risky: it produces broken rows as soon as a value contains a comma, a quote or a line break.

Method 3: MySQL Workbench or another GUI client

MySQL Workbench can export a query result grid or a whole table (through its Table Data Export Wizard) to CSV. Column headers are normally included. The available options and their defaults depend on the version, so check the delimiter, quoting and header settings in the export dialog. This is a reasonable choice for one-off exports, but it is harder to repeat consistently than a scripted command.

What the export actually changes

Exporting to CSV or TSV turns typed database values into plain text separated by delimiter characters. Row order and the characters in each value stay the same unless escaping rules change them. Several things are lost or reinterpreted along the way:

  • Data types are not stored. Numbers, dates and strings all become text, and the program that opens the file decides how to interpret them.
  • NULL has no standard CSV form. INTO OUTFILE writes \N with the default escape settings, batch mode writes NULL, and other tools may write an empty field. An empty string and a NULL can become hard to tell apart.
  • Escaping conventions differ. MySQL's default escape character is a backslash. Many CSV readers instead expect a double quote inside a quoted field to be written as two double quotes. Before you rely on any method, test it on rows that contain commas, quotes, line breaks and backslashes.
  • Character encoding depends on your settings. Specify the character set explicitly, as in the CHARACTER SET clause above, so that non-ASCII text is not silently converted.
  • In a UNION header, the header literals and the data share result columns. The header is still written correctly, but if any later processing expects numeric types, it must skip the first line.

Will the file stay usable after sharing?

Plain delimited text copies, transfers and versions well, and nearly any spreadsheet, script or text editor can open it. Problems usually appear in the program that interprets the file, not in the file itself. Spreadsheet applications may convert values automatically: they can drop leading zeros from codes, show long identifiers in scientific notation, or reformat strings that look like dates. Some may also misdetect the encoding or the delimiter. Behavior varies by application, version and regional settings, and no tests are reported here. Open a sample export in the program your recipient actually uses, and check that it has a non-ASCII value, a value with leading zeros and a value containing the delimiter.

On accessibility, a CSV file is text, so screen readers can read it. That works much better than a screenshot of a result grid. How well the header row gets associated with each cell, however, depends on the program used to open the file, not on the CSV. If a reader only needs a summary, a short plain-text description or a properly marked-up table is often easier to navigate than a raw file.

Gaps and things to verify

No measurements, version-specific tests or destination-specific results were available for this review, so the guidance above relies on documented MySQL behavior and general CSV principles. Before you use any method in production, confirm three things for your MySQL version: the INTO OUTFILE syntax and the secure_file_priv value on your server, how your chosen method writes NULLs and embedded quotes, and how the receiving application reads the result.