To output MySQL query results in CSV (Comma Separated Values) format, you can use the SELECT INTO OUTFILE
statement in MySQL.
The SELECT INTO OUTFILE
statement allows you to select rows from a table and save the resulting rows to a file on the server. The file can be in a variety of formats, including CSV.
Here’s an example of how to use the SELECT INTO OUTFILE
statement to output MySQL query results in CSV format:
SELECT * INTO OUTFILE '/path/to/file.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM table_name;
In this example, we use the SELECT INTO OUTFILE
statement to select all rows from the table_name
table and save the results to a file named file.csv
on the server.
We use the FIELDS TERMINATED BY
option to specify that the fields in the file should be separated by a comma (,
), and we use the ENCLOSED BY
option to specify that the fields should be enclosed in double quotes ("
).
We use the LINES TERMINATED BY
option to specify that the lines in the file should be terminated by a newline character (\n
).
Note: The SELECT INTO OUTFILE
statement can only be used if the MySQL server has the FILE
privilege. Additionally, the file must be writable by the MySQL server.