<!-- How to Export SQL Query Results to CSV -->
<!-- Canonical: https://dataswitchpro.com/guides/export-sql-to-csv/ -->
> Export a table or query to CSV with headers in MySQL, PostgreSQL, SQL Server and SQLite, or convert a .sql dump without a database.

[Home](https://dataswitchpro.com/) › [Guides](https://dataswitchpro.com/guides/)

# How to Export SQL Query Results to CSV (MySQL, PostgreSQL, SQL Server, SQLite)

By the DataSwitch Pro team · November 20, 2026 · 4 min read

## Quick answer

In PostgreSQL use `\copy (SELECT ...) TO 'out.csv' WITH (FORMAT csv, HEADER true)`; in SQLite run `sqlite3 -header -csv app.db "SELECT ..." > out.csv`; in MySQL use `SELECT ... INTO OUTFILE` on the server or a client tool's export button; in SQL Server use SSMS's *Save Results As* or the `bcp` utility. If you only have a `.sql` dump file and no running database, extract its INSERT rows with a [SQL to CSV converter](https://dataswitchpro.com/sql-to-csv/).

Sooner or later, someone asks for “the data in Excel”. Every database can write query results to CSV, but the commands differ, and some of them quietly skip the header row or fail to quote values that contain commas. Here is the reliable way for each one.

## PostgreSQL

### psql

```
\copy (SELECT id, name, email FROM customers WHERE active) TO 'customers.csv' WITH (FORMAT csv, HEADER true)
```

`\copy` runs in the psql client and writes the file on *your* computer. The SQL command `COPY ... TO '/path/file.csv'` writes on the database server instead and needs elevated privileges. CSV mode quotes values containing commas, quotes or line breaks automatically.

## SQLite

### Command line

```
sqlite3 -header -csv shop.db "SELECT * FROM orders;" > orders.csv
```

Inside the interactive shell, the same is done with `.headers on`, `.mode csv`, `.output orders.csv`, the query, and `.output stdout` to switch back.

## MySQL and MariaDB

### MySQL (file written on the server)

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

`INTO OUTFILE` writes on the database server, only into the directory allowed by `secure_file_priv`, and does not include a header row. On managed or shared hosting it is often disabled. Practical alternatives:

- **MySQL Workbench**: run the query, then click *Export recordset to an external file* above the result grid and choose CSV.
- **phpMyAdmin**: open the table or run the query, then *Export → CSV*, ticking “Put columns names in the first row”.
- **Command line**: `mysql --batch -e "SELECT ..." db > out.tsv` gives a tab-separated file with headers, which Excel and converters open fine.

## SQL Server

- **SSMS**: run the query with results to grid, right-click the results and choose *Save Results As… → CSV*. To include headers and quote values that contain commas, enable both options under *Tools → Options → Query Results → SQL Server → Results to Grid* and open a new query window.
- **bcp**: `bcp "SELECT id, name FROM shop.dbo.customers" queryout customers.csv -c -t, -S myserver -T` is fast for large exports, but writes no header row and does not quote fields.
- **PowerShell**: `Invoke-Sqlcmd -Query "..." | Export-Csv customers.csv -NoTypeInformation` produces properly quoted CSV with headers.

## When you only have a .sql dump

Backups and exports from hosting panels are often a `.sql` file full of `INSERT` statements. You do not need to install a database to read it: the [SQL to CSV converter](https://dataswitchpro.com/sql-to-csv/) reads the `INSERT INTO ... VALUES` rows of a table and turns them into CSV, using the column list as headers. Paste the statements of one table at a time so every row has the same columns.

## Opening the CSV in Excel correctly

- Write UTF-8; add a byte-order mark if the file is meant for Excel, or accented characters may break (see [garbled characters in CSV](https://dataswitchpro.com/guides/fix-garbled-characters-csv-excel/)).
- Columns with IDs or postcodes lose their leading zeros when Excel opens a CSV. Convert to a real workbook with [CSV to Excel](https://dataswitchpro.com/csv-to-excel/) or import with column types — see [keeping leading zeros](https://dataswitchpro.com/guides/keep-leading-zeros-csv-excel/).
- Export dates as `YYYY-MM-DD` so every regional setting reads them the same way.
- NULL values usually become empty fields (MySQL's `INTO OUTFILE` writes `\N`). Decide what the reader expects.

**Try it on your own file.** Free, private, and processed in your browser.

[SQL to CSV](https://dataswitchpro.com/sql-to-csv/)[CSV to Excel](https://dataswitchpro.com/csv-to-excel/)[CSV to SQL](https://dataswitchpro.com/csv-to-sql/)[CSV to JSON](https://dataswitchpro.com/csv-to-json/)

## Frequently asked questions

### How do I include column names in a MySQL export?

INTO OUTFILE has no header option. Use a client export (Workbench, phpMyAdmin, mysql --batch), or add a UNION ALL with a row of column names.

### Why does my CSV break when a value contains a comma?

The export did not quote fields. Use CSV mode (PostgreSQL, SQLite), ENCLOSED BY in MySQL, or enable quoting in SSMS.

### Can I export directly to Excel instead of CSV?

Some GUI tools can. Otherwise export CSV and convert it to .xlsx, which also preserves text columns such as IDs.

### How do I export a very large table?

Use the command-line tools (\copy, bcp, mysql --batch) rather than GUIs, and filter or split the export if Excel's 1,048,576-row limit is a concern.

## More guides

- [How to Keep Leading Zeros (and Long Numbers) When Opening CSV in Excel](https://dataswitchpro.com/guides/keep-leading-zeros-csv-excel/)
- [Why Your CSV Opens in One Column in Excel (and How to Fix It)](https://dataswitchpro.com/guides/csv-opens-in-one-column-excel/)
- [Fix Garbled Characters (Ã©, â€™, Ã¨) in CSV Files Opened in Excel](https://dataswitchpro.com/guides/fix-garbled-characters-csv-excel/)
- [How to Import a CSV File into MySQL, PostgreSQL, SQL Server or SQLite](https://dataswitchpro.com/guides/import-csv-into-sql-database/)
