To output MySQL query results in CSV format, you can use one of the following methods depending on your workflow and access permissions:
1. Using the MySQL Command-Line Client
Method 1: Direct Export with SELECT ... INTO OUTFILE
Run the query and save the result directly to a CSV file on the MySQL server:
SELECT *
FROM your_table
WHERE your_conditions
INTO OUTFILE '/path/to/output.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
Notes:
- Requires
FILE
privilege and write access to the server directory. - File paths are server-side (e.g.,
/var/lib/mysql/files/output.csv
). - Use
SHOW VARIABLES LIKE 'secure_file_priv';
to find allowed directories.
Method 2: Client-Side CSV Formatting
Redirect query results to a CSV file from your local machine (no server permissions needed):
mysql -u username -p -D database_name \
--batch --skip-column-names \
-e "SELECT * FROM your_table" \
| sed 's/\t/","/g; s/^/"/; s/$/"/;' \
> output.csv
Breakdown:
--batch
: Output in tab-separated format.--skip-column-names
: Exclude headers.sed
: Replace tabs with","
, wrap lines in quotes.
2. Using MySQL Workbench or phpMyAdmin
MySQL Workbench:
- Run your query.
- Click Export (grid icon) > Export to CSV.
phpMyAdmin:
- Run your query.
- Click Export > Format: CSV.
3. Programmatic Export (e.g., Python/PHP)
Python Example:
import csv
import mysql.connector
conn = mysql.connector.connect(user='user', password='pass', host='localhost', database='db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM your_table")
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([i[0] for i in cursor.description]) # Write headers
writer.writerows(cursor)
4. Include Headers Automatically
Add column headers using SQL:
SELECT 'Column1', 'Column2', 'Column3' # Manually specify headers
UNION ALL
SELECT Column1, Column2, Column3
FROM your_table
INTO OUTFILE '/path/output.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"';
Key Considerations
- Escaping Quotes: Use
ENCLOSED BY '"'
to handle commas/quotations in data. - NULL Values: Represented as
\N
by default. UseIFNULL(column, '')
to replace NULLs. - Large Datasets: Use
LIMIT
for testing before full exports.
Example Output
Query:
SELECT id, name, email
FROM users
WHERE status = 'active'
INTO OUTFILE '/tmp/users.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
CSV Output:
"1","Alice","alice@example.com"
"2","Bob","bob@example.com"
Summary
Method | Use Case | Pros | Cons |
---|---|---|---|
INTO OUTFILE | Server-side exports | Fast, no client processing | Requires server file permissions |
Command-line redirection | Local exports without server access | No special privileges required | Manual formatting |
Python/PHP scripts | Custom workflows (e.g., automation) | Full control over formatting | Requires coding |
GUI Tools | Quick exports for small datasets | User-friendly | Not scalable for large data |