How to export a MySQL database to a CSV file
Use SELECT INTO OUTFILE to export a MySQL table to CSV directly, ensuring the MySQL user has FILE privilege and write access to the server's file system.
To export a MySQL database table to a CSV file, you can use the SELECT ... INTO OUTFILE statement directly in MySQL. This method is efficient and doesn't require additional tools. Below are the steps and syntax to do it properly.
1. Use SELECT INTO OUTFILE
This SQL command exports query results directly to a CSV file on the server's filesystem. Make sure you have write permissions in the target directory and that the MySQL user has the FILE privilege.
SELECT column1, column2, column3 INTO OUTFILE '/path/to/your/file.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM your_table_name WHERE conditions (optional);
Example:
SELECT id, name, email INTO OUTFILE '/tmp/users.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM users;
The resulting file will be comma-separated, with each field enclosed in double quotes and each row on a new line.
2. Key Options Explained
Customize the output format using these clauses:
- FIELDS TERMINATED BY ',' – sets the delimiter (use '\t' for tab).
- ENCLOSED BY '"' – wraps fields in quotes (helpful for text containing commas).
- LINES TERMINATED BY '\n' – sets line breaks (use '\r\n' for Windows).
- ESCAPED BY '\\' – defines escape character (defaults to backslash).
3. File Location and Permissions
The file is saved on the MySQL server machine, not your local client. The path must be writable by the MySQL server process. Common safe paths include /tmp
or /var/lib/mysql-files/
. Avoid directories outside MySQL’s allowed file operations.
If you get an error like "File '...' already exists", delete the file first or choose a new name.
4. Alternative: Export via Command Line (mysqldump formatting)
If you need more control or are scripting, use mysql
client from the terminal:
mysql -u username -p -e "SELECT * FROM your_db.your_table;" --batch --raw | sed 's/\t/,/g' > output.csv
This outputs tab-separated results and converts tabs to commas using sed
. Add sed 's/^/"/;s/$/"/;s/,/","/g'
if you want fields quoted.
Basically just pick the method that fits your environment. Using SELECT INTO OUTFILE
is usually the simplest if you have server access.
The above is the detailed content of How to export a MySQL database to a CSV file. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The answer is: MySQL's CASE statement is used to implement conditional logic in query, and supports two forms: simple and search. Different values can be dynamically returned in clauses such as SELECT, WHERE, and ORDERBY; for example, in SELECT, classification of scores by fractional segments, combining aggregate functions to count the number of states, or prioritizing specific roles in ORDERBY, it is necessary to always end with END and it is recommended to use ELSE to handle the default situation.

Create a shell script containing the database configuration and mysqldump command and save it as mysql_backup.sh; 2. Store MySQL credentials by creating ~/.my.cnf file and set 600 permissions to improve security, modify the script to use configuration file authentication; 3. Use chmod x to make the script executable and manually test whether the backup is successful; 4. Add timed tasks through crontab-e, such as 02/path/to/mysql_backup.sh>>/path/to/backup/backup.log2>&1, realize automatic backup and logging at 2 a.m. every day; 5.

INSERT...ONDUPLICATEKEYUPDATE implementation will be updated if it exists, otherwise it will be inserted, and it requires unique or primary key constraints; 2. Reinsert after deletion of REPLACEINTO, which may cause changes in the auto-increment ID; 3. INSERTIGNORE only inserts and does not repetitive data, and does not update. It is recommended to use the first implementation of upsert.

EXPLAINinMySQLrevealsqueryexecutionplans,showingindexusage,tablereadorder,androwfilteringtooptimizeperformance;useitbeforeSELECTtoanalyzesteps,checkkeycolumnsliketypeandrows,identifyinefficienciesinExtra,andcombinewithindexingstrategiesforfasterqueri

Subqueries can be used in WHERE, FROM, SELECT, and HAVING clauses to implement filtering or calculation based on the result of another query. Operators such as IN, ANY, ALL are commonly used in WHERE; alias are required as derivative tables in FROM; single values must be returned in SELECT; related subqueries rely on outer query to execute each row. For example, check employees whose average salary is higher than the department, or add the company average salary list. Subqueries improve logical clarity, but performance may be lower than JOIN, so you need to ensure that you return the expected results.

Use UTC to store time, set the MySQL server time zone to UTC, use TIMESTAMP to realize automatic time zone conversion, adjust the time zone according to user needs in the session, display the local time through the CONVERT_TZ function, and ensure that the time zone table is loaded.

MySQL can calculate geographical distances through the Haversine formula or the ST_Distance_Sphere function. The former is suitable for all versions, and the latter provides easier and more accurate spherical distance calculations since 5.7.

UseCURDATE()togetthecurrentdateinMySQL;itreturns'YYYY-MM-DD'format,idealfordate-onlyoperations.
